mercredi 31 janvier 2018

Ember loading state not triggered on transitionTo

If I use a transitionTo on a route with a slow model hook, the loading.hbs state never gets triggered (I have loading.hbs files at all of the levels -- cluster, cluster.schedule and cluster.schedule.preview_grid). I tried renaming the one at cluster.schedule preview_grid-loading.hbs with no luck.

On the transitionTo, there is no model or model id passed in, just the route:

viewPreviewGrid: function() { this.transitionTo('cluster.schedule.preview_grid'); },

I also have a loading action defined as follows:

loading(transition) {
    var controller = this.controller;
    if (!Ember.isNone(controller)) {
        this.controller.reset();
    }
    transition.promise.finally(function() {
        NProgress.done();
    });
}

During the transitionTo call the page just stays on the previous route until the promises in the model hook resolve, and then it transitions to the other route. If I refresh the page, the loading state gets triggered just fine. Is this a known behaviour for transitionTo?




Ember Data does not recognise ID in JSON response

I've been trying to figure this out for the past couple of hours and I thought it might be best to ask for some help at this point. The following error is being thrown after my Ember App posts to my Rails API:

Assertion Failed: Your outcome record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.

What's strange is that my API is returning a JSON response with an ID (see below).

{
  "producer_objective_outcome": {
    "id":27,
    "type":"ProducerObjectiveOutcome",
    "title":"New outcome"
    "owner": {
      "id":6,
    }
  }
}

As you might already have picked up, ProducerObjectiveOutcome is a subclass of Outcome.

In both my Ember App and Rails API, I have setup ProducerObjectiveOutcome to inherit from Outcome. In my Ember App particular, this is what the model looks like:

// app/models/producer-objective-outcome.js

import Outcome from "./outcome";

export default Outcome.extend({

});

Nothing fancy going on here – I thought it was all pretty straight forward – but for some reason, that error is coming up. I'm hoping one of you marvelous people can help me out with this!

Thanks in advance!




How to submit Linkedin search query from javascript

I am new in creating chrome extension. Now I am creating chrome extension in which I need to search some value in linkedin search box. So can anyone tell me how can do that? It is a form created in Ember.js, if it is of JavaScript I would have done it easily. Please suggest me how can I send some value in the search box and then submit it to display the search result using JavaScript

Thanks in advance




Why is Ember not rendering the template?

I just started playing around with Ember and stumbled upon a problem, of which I believe is pretty basic. Still, I can't figure out what's going on.

Specifically, after creating a new route with a dynamic segment, the template is never rendered, when visiting the according URL.

I'd like to visit localhost:8080/tournaments/1 and render a template named deathmatch.

Basically, I just created a new Ember-App and executed ember generate route deathmatch using ember-cli. After that, I changed the code inside the function passed to Router.map.

router.js

Router.map(function() {
    this.route('deathmatch', {path: '/tournaments/:tournament_id'});
});

templates/deathmatch.hbs

<span>Just some test output</span>

For testing purposes, I removed the second argument in this.route completely and visited localhost:8080/deathmatch. This works just as expected. Afterwards, I re-added the second argument, to be {path: ':tournament_id'}only. Visiting localhost:8080/1 also worked just fine. However, using the code as shown above, an empty page is being rendered.

Apparently, I'm misunderstanding Ember's documentation. So, can anyone point me in the right direction, as of what I'm not seeing here?




What's best between ember-addon and libraries

I would like to know, in a optimisation and reliable way:

would it be better to use ember-addon OR librairies and import it through ember-cli-build.js

For exemple, would it be better to install ember-cli-moment or npm install moment and import it in ember-cli-build.js like so app.import(node_modules/path_to_moment.js)

I know that the app.import may oversize the vendor.js size by copying all the content of the lib in vendor file. What about the ember-addonn way ? Is impacting the size of vendor.js too ?

I don't take in consideration the fact that you have some helper with the ember-addon way.

I'm only seeing the optimisations and the size of the final app.

What's your opinion ?
Thanks and have a good day !




Ember app `setTimeout` not working on screen display turned off

I am calculating the idle time of my application using setTimeout or 'Later` function. I am getting the issue when the user switch off the screen.

example: when timeout reach 10min, i would like to logout. But when user switch of the screen and opens back at 30min, still not my app logged out because of timeout was suspended.

shortly, how can i run my setTimeout still the display screen switched off in any of the mobile phone?




mardi 30 janvier 2018

Ember Computed Property Slow and Inconsistent

I have an app that displays videos and allows users to rate the videos. An average rating and the number of times the video has been rated are displayed beneath it. To calculate these I have added computed properties to each model. The average property relies on the sum and length computed properties.

/*global Ember */
import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  url: DS.attr('string'),
  ratings: DS.hasMany('userrating'),
  users: DS.hasMany('user'),
  rated: DS.attr('boolean'),

  // maps through ratings objects and pulls out the rating property
  // returns an array of integers that represent all of one videos ratings
  numRatings: Ember.computed.mapBy('ratings', 'rating'),

  // returns the sum of a videos ratings
  sum: Ember.computed.sum('numRatings'),

  // returns the number of ratings a video has
  length: Ember.computed('numRatings', function () {
    return this.get('numRatings').length;
  }),

  // returns true if the video has only been rated once
  // this is used to determine if '1 user' or '2 users' etc.
  // should be displayed
  one: Ember.computed('length', function () {
    if (this.get('length') === 1) {
      return true;
    }
  }),

  // returns the average rating of a video
  avg: Ember.computed('length', 'sum', function () {
    return Math.round(this.get('sum') / this.get('length'));
  })
});

I have noticed that sometimes the sum is displayed in place of the average. This usually happens only for a second and then the average correctly displays, but every once in a while the average does not display. Today, all videos except for one were displaying correctly, but that one video was displaying ’33/5’ as the average rating.

Why is this happening? Should I not build Ember computed properties to rely on each other? Is this just a problem with the browser being slow? I am loading a bunch of videos and images.

I am pretty new to web development in general and this is my first Ember app.

Thanks!




How to test the function that a controller action calls

I have an action that calls another function, within that function I use regex with javascript's string replace. I am running into the issue of testing regex-replace part of it. I keep getting "Cannot read property ‘replace’ of undefined" when I am running my test case. Here is my example:

actions:{
someAction(){
someFunction();}
},
someFunction(){
url = url.replace(/\/$/, '');}




Javascript access parameter inside custom sort function

I have a custom sort function defined & call it as below;

myArr.sort(this.sortArrayBy, key);

sortArrayBy: function(a, b) {

    let param = this.get('sortKey'); //How do I get this value here ? cannot pass it as param OR even access via 'this'

    if (a.param < b.param)
        return -1;
    if (a.param > b.param)
        return 1;
    return 0;
},

I want to pass an additional param inside that function. How do I get access to that class attribute ?

P.S: This code is inside my Ember controller class




Is there any way to do nested handlebars in ember templates?

inside ember templates, I have called a helper & component

Is there any way to do html escape for both together?




HTML Safe for more than one handlebar

I am doing string parsing inside ember template. so, my code look like this

for {
 
 
}

So, basically if below is the string This is John I wanted John to be highlighted & mouse over John will take you to some other link.

Here, problem I face is.. 1) As i am breaking the string into 2, strings that starts with div tag are getting broken. Html escape autocloses the div tag. which then result in display output like this

This is
John (highlighted)

Instead of "This is John" Is there any way to stop auto closing?

2) Is there any way to do combined html escape for both helper & component inside templates?

3) Is there any way to bring in helper-component as a string from JS helper , so that we can execute it inside template ?




lundi 29 janvier 2018

Ember importing value and compute function

I have range with currentValue displayed in span. I'm trying to import this value to compute function, make a calculation and return back. I stacked in compute.

range.hbs

<input
type="range"
onchange=
class="form-control"
value=""
min="1"
max="99"
/>

<span class="tag tag-pill tag-info">
   % - %
</span>

range.js

export default FormComponent.extend({

deltaValue: computed('currentValue', function() {
    var newValue = 100 - this.get('currentValue');  
    return newValue;
  })
});




How to use Foundation Icon Fonts in Ember application

Does anybody know how to enable Foundation Icon Fonts in Ember App ? I tried to put it in vendor folder, in public folder, - still does not work with the below code example:

# application.hbs

<ul class="menu">
      <li><a href="#"><i class="fi-list"></i><span>One</span></a></li>
      <li><a href="#"><i class="fi-list"></i><span>Two</span></a></li>
      <li><a href="#"><i class="fi-list"></i><span>Three</span></a></li>
      <li><a href="#"><i class="fi-list"></i><span>Four</span></a></li>
    </ul>

I also added the import of the above CSS in ember-cli-build.js: app.import('vendor/foundation-icons/foundation-icons.css');




Ember JS: Assertion Failed: `AdapterError` expects json-api formatted errors array

I am making my first Ember/Phoenix app using JSONAPIAdapter. When doing a post request Ember responds with Assertion Failed: AdapterError expects json-api formatted errors array.

Below is the relevant code:

adapter/application.js

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import config from '../config/environment';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {

});

serializers/application.js

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({

});

request payload:

{
    "data": {
        "attributes": {
            "name": ""
        },
        "relationships": {
            "user": {
                "data": {
                    "type": "users",
                    "id": "1"
                }
            }
        },
        "type": "listings"
    }
}

response payload:

{"errors":{"name":["can't be blank"]}}

Why does Ember keeps giving me this error?




Ember abort queryParams transition

I am trying to capture transitions to run a few checks before carrying on. In almost all of my use cases, I can accomplish it just fine.

However, I have one set of links that only change the queryParams. When I try transition.abort() on this link, I get an error.

Here is my template:

next

And, on the route:

actions: {
    willTransition (transition) {
      transition.abort();
    }
}

The error:

transitionByIntent@https://192.168.1.3/assets/vendor.js:62857:16
refresh@https://192.168.1.3/assets/vendor.js:62948:14
refresh@https://192.168.1.3/assets/vendor.js:37404:14
queryParamsDidChange@https://192.168.1.3/assets/vendor.js:37123:13
triggerEvent@https://192.168.1.3/assets/vendor.js:39417:13
trigger@https://192.168.1.3/assets/vendor.js:64310:7
fireQueryParamDidChange@https://192.168.1.3/assets/vendor.js:63092:7
getTransitionByIntent@https://192.168.1.3/assets/vendor.js:62785:5
transitionByIntent@https://192.168.1.3/assets/vendor.js:62855:16
refresh@https://192.168.1.3/assets/vendor.js:62948:14
refresh@https://192.168.1.3/assets/vendor.js:37404:14
queryParamsDidChange@https://192.168.1.3/assets/vendor.js:37123:13
triggerEvent@https://192.168.1.3/assets/vendor.js:39417:13
trigger@https://192.168.1.3/assets/vendor.js:64310:7
fireQueryParamDidChange@https://192.168.1.3/assets/vendor.js:63092:7
getTransitionByIntent@https://192.168.1.3/assets/vendor.js:62785:5

I truncated the error message. Basically it looks like it is trying over and over and over again to make the transition.

Furthermore, despite the errors, the page does refresh (which it shouldn't) based upon the new parameters.

QUESTION

How to capture a transition on JUST a change in the query parameters, so that I can decide to proceed or abort?

I know there is the queryParamsDidChange hook. I wish there was queryParamsWillChange.




dimanche 28 janvier 2018

ember.js triggering an action based on conditional

I have an action that I want to trigger in my component hbs file if a conditional returns true. For example, If my component.js file looks like this:

export default Ember.Component.extend({
  toggleMe: false,
  actions: {
    changeValue() {
      return this.toggleProperty('toggleMe');
    }
  }
});

I want to call that changeValue action in my hbs file. This is the approach that I have tried in my component.hbs file:

{#if model.property}}
    


I'm getting an error

"Assertion Failed: Action passed is null or undefined"




EmberJs and passport-google-oauth

i am new to emberjs and passport js google oauth2. I am trying to create a authentication with an third party app like google to handle my password. So far, i’ve tested my backend (nodejs) and it persist the data user. My issue is that, how can i transfer my data (user data) to the front-end(emberjs) with the callback url (/auth/google/callback). My second issue, when i try to make an ajax call get (localhost:3000/auth/google), it doesn't redirect me to the google page to login...instead it refresh my UI.

User-component.js (Emberjs front-end

server.js, where i implement google passport strategy




Error in deploying ember app on gh-pages by Travis

I want to deploy my front-end made in ember js on gh-pages after successful Travis Build. But when Travis runs it gives error as follows :

after_success

$ bash ./script/gh_deploy.sh cleaning up cleaning up... remote: Invalid username or password. fatal: Authentication failed for 'https://ParthS007:undefined@github.com/fossasia/badgeyay/' Error: git push https://ParthS007:undefined@github.com/fossasia/badgeyay gh-pages exited with nonzero status Error: git push https://ParthS007:undefined@github.com/fossasia/badgeyay gh-pages exited with nonzero status at ChildProcess.<anonymous> (/home/travis/build/fossasia/badgeyay/frontend/node_modules/ember-cli-deploy-git/lib/run.js:19:19) at emitTwo (events.js:106:13) at ChildProcess.emit (events.js:191:7) at maybeClose (internal/child_process.js:920:16) at Process.ChildProcess._handle.onexit (internal/child_process.js:230:5)Pipeline aborted Done. Your build exited with 0. This is the link to files which I have changes in my Pull request for gh-pages deployment https://github.com/fossasia/badgeyay/pull/529/files Please suggest what should be changed for successful gh-pages deployment. Thanks in advance




samedi 27 janvier 2018

Building an Ember project for Andriod

Hi I'm trying to build an Ember app for Android. I'm on a Mac and in Android Studio 3 I don't have a Tools -> Android menu so I'm using 2.3.3. I have a device created and can run the emulator.

The command I'm using is:

ember cordova run --platform=android

This is the error I get:

(node:1929) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Source directory does not exist: /Users/name/Sites/project/cordova/platforms/android/platform_www (node:1929) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I do have a cordova/platforms/android/platform directory but I do not have a platform_www directory.

I have run ember cordova:build --platform=android

I don't see a flag to set the platform directory? Any ideas on what I'm doing wrong?

Thanks!




reinitialize the component with button click in ember

i have installed jquery builder in my ember app. I have to initialize the builder twice in the same template.

First i have to initialize when page is routed to the particular id. here is my hbs code>>>

 <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 px-0" >
                                                
                                                    
                                                        <div id="showBuilderBase"></div>
                                                        
                                                     
                                                    
                                            </div> 

where query-builder-comp is a component.

Second i want to show the query builder into a modal which will open with click of a button. here is my hbs code.>>

   <!-- Central Modal Medium Info -->
    <div class="modal fade" id="queryBuilderModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-notify modal-info modal-lg" role="document">
            <!--Content-->
            <div class="modal-content">
                <!--Header-->
                <div class="modal-header py-1 blue lighten-3">
                    <p class="heading lead">Story Filter</p>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true" class="white-text">&times;</span>
                    </button>
                </div>

                <!--Body-->
                <div class="modal-body">
                    <div class="row">

                                          </div> 
                                          <div class="card-content remove-space builderHt" id="buildRuleTop">
                                            <div class="mx-0 mb-1">
                                            
                                                 
                                                   <div id="showBuilderModal"></div>
                                                    
                                                   
                                             
                                                 <div class="row grey-text indicatorMessage p-3 brown lighten-5"><i class="fa fa-hand-o-up fa-lg purple-text" aria-hidden="true"></i>&nbsp;&nbsp;Please select the collection name to begin.</div>    
                                                    
                                            </div> 
                                          </div>
                                          </div> 

                    </div>
                </div>

                <!--Footer-->
                <div class="modal-footer justify-content-center py-0">
                    <a type="button" class="btn btn-warning btn-sm" >Save </a>
                    <a type="button" class="btn btn-outline-secondary-modal waves-effect btn-sm" data-dismiss="modal">Cancel</a>
                </div>
            </div>
            <!--/.Content-->
        </div>
    </div>
    <!-- Central Modal Medium Info-->

but the query builder is no showing up in the modal. how to deal with this issue.




Images from public/assets folder in Ember returning 404

I am trying to create my first ember app, and I started fleshing out the landing page. I tried to create a billboard section at the top and placed an image in it with an inline style

background-image: url('/assets/images/photo.png')

I read that you are supposed to put all your images in an assets folder in the public directory which I did, but I am getting a 404 response for that image.

http://localhost:4200/assets/images/photo.png




vendredi 26 janvier 2018

Display Ember.Object on the screen in Ember.js

I'm green in Ember. I've followed the quickstart and I run those commands:

ember new ember-quickstart
ember g route index

I've created a basic Ember application with an index route. I've wanted to use this route to display the date on the screen. So I've created some EmberObjects in it.

app/routes/index.js

import Object from '@ember/object';
import Route from '@ember/routing/route';

function getCompaniesJSON() {
  return [
    {
      "title": "Danone",
      "upvotes": 92,
      "downvotes": 62
    },
    {
      "title": "Bakoma",
      "upvotes": 58,
      "downvotes": 68
    },
    {
      "title": "Zott",
      "upvotes": 62,
      "downvotes": 54
    },
    {
      "title": "Jana",
      "upvotes": 72,
      "downvotes": 56
    }
  ];
}

function totalVotes(company) {
  return company.get('upvotes') + company.get('downvotes');
}

var Company = Object.extend({
  score: function() {
    return (this.get('upvotes') * 100 / totalVotes(this)).toFixed(2);
  }
});

var AppModel = Object.extend({
  topCompanies: function() {
    return this.get('companies').sort(function(a,b) {
      return totalVotes(b) - totalVotes(a);
    }).slice(0, 3);
  }.property('companies.@each.upvotes', 'companies.@each.downvotes')
});

var appModel = AppModel.create({
  companies: getCompaniesJSON().map(function(json) {
    return Company.create(json);
  })
});

export default Route.extend({
  topCompanies: appModel.topCompanies
});

app/templates/index.hbs

<ul>

  <li> %</li>

</ul>

Above code is displaying nothing. No errors in the console. I'd like to display topCompanies on the screen, but I've no idea how to pass this variable correctly. Is a Route a correct place to do it? Or I should use Component/Controller?




Read String Array in Django API

I have EmberJS front-end which calls Django REST API. I am passing string array from front-end to the API as shown below:

Back-end Request http://localhost:8000/api/v1/User/search/?active=true&city%5B%5D=newyork&city%5B%5D=chicago&city%5B%5D=boston

HTML Decoded http://localhost:8000/api/v1/User/search/?active=true&city[]=newyork&city[]=chicago&city[]=boston

Some how I am not able to get rid of the extra %5B%5D (which is square brackets) from this request as EmberJS automatically adds that as the parameter is passed as string array. I searched over several forums but did not get a solution for it.

How to read the string array (City parameter) in Django API and get all passed values from EmberJS front-end?




ember data lost data after reload

I use ember-data, and every time my page is reloaded, I lose my data in the store. I am implementing an external payment, after the payment page (external). my user returns to the confirmation page but with an empty store.

Can you help me please?




How Udacity forums track read time?

I'm wondering what algorithm or technique that Udacity use to keep track of their users' read time in the forums? like in the image here




Accessing this.$() in qunit test

I’ve created a small mixin that helps a component to be hidden when the user clicks outside of the component. I’d now like to add a test for it, where I trigger a click event outside a component that extends the mixin.

All I want to test is that a method called onOutsideClick is called. For this, I’m trying to draw inspiration from: https://github.com/nucleartide/ember-outside-click

But when I do this:

const HideOnOutsideClickObject = Ember.Component.extend(HideOnOutsideClick, {
})

test('click outside', function(assert) {
  const element = this.$()[0]

  const event = document.createEvent('MoseEvents')
  event.initEvent(event, true, true)
  element.dispatchEvent(event)

  assert.ok(HideOnOutsideClickObject.onOutsideClick)
})

I get an error saying that this.$() is not a function. What am I missing?

I’ve of course imported the mixin as I should.




jeudi 25 janvier 2018

Ember loading state not triggered in transitionTo

If I use a transitionTo on a route with a slow model hook, the loading.hbs state never gets triggered. (I have loading.hbs templates at every level in the hierarchy.) If I refresh the page, the loading state gets triggered just fine.

During the transitionTo call the page just stays on the previous route until the promises in the model hook resolve, and then it transitions to the other route. Is this a known behaviour for transitionTo?

Side note -- the model hook returns an Ember.RSVP.hash with 3 API calls, that each return promises. I have tried simplifying this model hook to return a simple promise with a timeout, with no luck.




Ember: Relationship link related data not loading / disappearing

I'm experiencing somewhat of a bug with Ember/Ember-data. Here's my scenario:

  1. Client lands on / route and Ember loads data from /api/v1/videos?limit=8. The response comes from a rails-api backend using active_model_serializers which ensures the response is JSON API compliant. Now the store has 8 arbitrary videos loaded into it.

  2. Each video component in the DOM has a link to a user page (the user hasMany videos. Client clicks on a link-to which navigates to /stores/1 which represents a user with ID 1

  3. The model hook for that route just loads a single user record. The user record has the following payload:

{
    "data": {
        "id": "1",
        "relationships": {
            "videos": {
                "data": [],
                "links": {
                    "related": "/api/v1/videos?user_id=1"
                }
            },
        },
        "type": "users"
    }
}

The problem is that ember does not automatically send the request for /api/v1/videos?user_id=1 (presumably because a similar request /api/v1/videos?limit=8 already happened).

If I directly load the /stores/1 page then ember is smart and auto-loads data from the /api/v1/videos?user_id=1 endpoint.

I suspect that Ember is being fooled by the fact that a similar request to the videos endpoint already happened with different query parameters. The end result is that my app does not show any data on the user page.

One way to fix this is to populate "data": [], with video IDs which will cause ember to send n requests for n items. This works but is not acceptable for a large scale app where a user page might have 100 videos.

How can I fix this?




Adding a smooth transition to d3 pie chart in Ember

I have a D3 pie chart that does almost everything I want it to do. It refreshes when the data changes and renders correctly.

I am having trouble adding a transition to the initial render and to the re-render when the data changes. I'd like to add a similar animation to the one visible here that was offered as a response to this question but I only receive 'Error: attribute d: Expected moveto path command ('M' or 'm') in the console when I try.

I tried to create a twiddle but couldn't get it to represent correctly. Full code for the component is here:

export default Component.extend({

  didInsertElement() {

    this.pieChart();
  },

  didUpdateAttrs() {
    this.pieChart();
  },
  pieChart() {
    let data = this.get('data');
    let div = select('body')
      .append("div")
      .attr("class", "tooltip"),
      width = 500,
      height = 500,
      donutwidth = 75,
      radius = Math.min(width, height) / 2,
      marc = arc().outerRadius(radius - 10).innerRadius(0),
      labelArc = arc().outerRadius(radius - 40)
      .innerRadius(radius - 40),
      color = scaleOrdinal(schemeCategory10),
      mpie = pie()
      .value((d) => {
        return d.count;
      })(data),

      svg = select(this.$('svg')[0])
      .append("g")
      .attr("transform", "translate(" + width / 2 + ", " +
        height / 2 + ")");

    let gUpdate = svg.selectAll("arc").data(mpie).exit().remove();

    let gEnter = svg.selectAll("arc")
      .data(mpie)
      .enter().append("g")
      .merge(gUpdate)
      .attr("class", "arc")

    //events
    gEnter
      .on("mousemove", function(d) {
        var mouseVal = mouse(this);
        div
          .html("Minutes: " + d.data.count + "</br>" + "Date: " + d.data.label)
          .style("left", (event.pageX + 12) + "px")
          .style("top", (event.pageY - 10) + "px")
          .style("opacity", 1)
          .style("display", "block");
      })
      .on("mouseout", function() {
        div.html(" ").style("display", "none");
      })
      .on('click', d => {
        let clickedLabel = d.data.label;
        let clickedCount = d.data.count;

        if (this.get('on-click')) {
          this.get('on-click')(clickedLabel)
        } else {
          if (clickedLabel === this.get('selectedLabel')) {
            this.set('selectedLabel', '');
            this.set('selectedCount', '');
          } else {
            this.set('selectedLabel', clickedLabel);
            this.set('selectedCount', clickedCount);
          }
        }
      })

    //path
    gEnter.append("path")
      .attr("d", marc)
      .attr("fill", (d, i) => {
        return color(i);
      })

    //Labels
    gEnter.append("text")
      .attr("transform", (d) => {
        return "translate(" +
          labelArc.centroid(d) + ")";
      })
      .text((d) => {
        return d.data.label;
      })
      .attr("text-anchor", "middle")
      .style("fill", "#FFF")
      .each((d) => {
        this.set('chartContextLable', d);
      })
  }
});

As I do not have a var path = declaration I tried to add the transition code in the gEnter.append("path") as follows:

 //path
    gEnter.append("path")
      .attr("d", marc)
      .attr("fill", (d, i) => {
        return color(i);
      })
      .transition()
   .duration(function(d, i) {
     return i * 800;
   })
   .attrTween('d', function(d) {
  var i = interpolate(d.startAngle+0.1, d.endAngle);
  return function(t) {
      d.endAngle = i(t);
    return arc(d);
  }
});

Then I receive the errors. Note that I am using ember-d3 to load the d3 modules which is why they don't have d3 namepaces.




this.set() not a function when clicking D3 Pie Chart Segments

I am trying to set a 'selectedLabel' when I click on my pie chart segments for use further in my component but I running into a 'this.set() is not a function' error that I have not seen before.

This answer suggests that the object I am trying to set the property for is not an Ember object and therefore needs to be changed with Ember.set(object, 'property' value) but this returns a null error.

I am using both this.get and this.set methods elsewhere in the same component so I'm not sure if there is a problem with his specific object or if I have a scoping issue.

Code:

let g = svg.selectAll("arc")
  .data(mpie)
  .enter().append("g")
  .attr("class", "arc")

  g
  .on("mousemove", function(d) {
    var mouseVal = mouse(this);
    div
      .html("Items: " + d.data.count + "</br>" + "Date: " + d.data.label)
      .style("left", (event.pageX + 12) + "px")
      .style("top", (event.pageY - 10) + "px")
      .style("opacity", 1)
      .style("display", "block");
  })
  .on("mouseout", function() {
    div.html(" ").style("display", "none");
  })

//attempt to set 'selectedLabel' property
      .on("click", function(d) {
        this.set('selectedLabel', d.data.label)
      })

Console logging 'this' in the click function gives me the correct segment of the pie chart.




mercredi 24 janvier 2018

Use closure actions, unless you need bubbling

I don't know what's wrong in my code. template/components/item.hbs:

<div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default"  disabled=></button>
        </div>
</div>

components/item.js:

import Component from '@ember/component';

export default Component.extend({
    buttonLabel: 'Save',

    actions: {
        buttonClicked(param) {
            this.sendAction('action', param);
        }
    }
});

Ember/library-app/app/components/item.js 8:13 error Use closure actions, unless you need bubbling ember/closure-actions




mardi 23 janvier 2018

Expanding D3 Pie Chart to fill SVG

I am trying to achieve two things:

  • Make the existing pie chart in my application fill the available SVG element it is rendered in.

  • Make the SVG element fill the size of the containing div it sits in
    so it is responsive.

In my bar charts I achieve this by setting ScaleLinear and ScaleBand ranges on the X and Y scale but this doesn't seem to be an option within the pie charts (and then setting the SVG element to a height and width of 100%).

Code:

export default Component.extend({

  tagName: 'svg',

   attributeBindings: ['width, height'],
   classNameBindings: ['baseClass'],

   a: null,
   baseClass: 'pie-chart',
   color: null,
   data: null,
   labelArc: null,
   height: 400,
   radius: null,
   svg: null,
   width: 400,
   donutwidth: 75,

setSvg() {
     const {
       height,
       baseClass,
       width,
     } = this.getProperties(
       'height',
       'baseClass',
       'width'
     );
     const svg = select(`.${baseClass}`)
       .attr('width', width)
       .attr('height', height)
       .append('g')

       .attr('transform', `translate(${width/2}, ${height/2})`);

     this.set('svg', svg);
   },

   _setG(svg, p) {
     return svg.selectAll('arc')
       .data(p)
       .enter()
       .append('g')
       .attr('class', 'arc');
   },

   _setPie(data) {
     const p = pie().padAngle(0.02).value((d) => d.count)(data);

     return p;
   },

// Template
<svg width='100%' height='100%'></svg>

Any help is gratefully appreciated




lundi 22 janvier 2018

ember.js RestAdapter How to define ajaxoptions

I customized RESTAdapter to connect to a RestHeart server (a RestFull web gateway server for mongodb):

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host:'http://127.0.0.1:8080',
  namespace: 'boards'
});

I created a model to test :

import DS from 'ember-data';

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

Everything works fine, but when I use the save method on a record (developer): I have a warning in the browser console :

The server returned an empty string for POST http://.../boards/Developer, which cannot be parsed into a valid JSON. Return either null or {}.

and the folowing error :

SyntaxError: Unexpected end of JSON input at parse () at ajaxConvert (jquery.js:8787) at done (jquery.js:9255) at XMLHttpRequest. (jquery.js:9548)

I know why : The RESTAdapter is waiting for a JSON response, and the restHeart server returns an empty response when adding => so jQuery causes an error when it tries to parse the null response.

With previous versions of ember-data, it was possible to set the dataType variable of jQuery ajax requests to '*' using the hook ajaxOptions this way:

export default DS.RESTAdapter.extend({
  ajaxOptions(url, type, options) {
    var hash = this._super(url, type, options);
    hash.dataType = "*";
    return hash;
  },
  host:'http://127.0.0.1:8080',
  namespace: 'boards'
});

With ember-data 2.16, ajaxOptions is now private, and I do not know how to modify the dataType variable... so that the null response is not parsed as a JSON response




How to retrieve User ID and Password using Ember Js

My requirement: Consider a client server web application. We have an LDAP server to authenticate.

When user logins to the application from a browser, we need to retrieve the current windows system user ID and password and then pass it to LDAP server for authentication.

Question: Where in windows does the windows system username and password is stored? How can we retrieve the user ID and the password using Ember. Please note that its not the web application userID and password, its the windows system userID and password.




Ember `partial` templating with component

I am trying to use a single component in multiple page with different content. for that, I am trying with partial templating approach. But I find my way is wrong. any one suggest me the correct way?

name of route : my-route and my-service both are using same component called my-component. my component always having some default info too.. but partially how show different content on different page?

my partials are in template partials folder.

here is my try :

<h2>This is my Route page</h2>

 <!-- default content should be here -->



here is my live demo: Live Demo in Twiddle




Using Ember component helper in block form

In my Ember app, I want to dynamically render my grid component (block form) as below


    


Now I want to be able to do the above using the component helper (since the grids will be dynamic)


                                


How can I achive the above block form with the component helper ?




dimanche 21 janvier 2018

Ember JS: Service - Get data from Socket.io

This is what I'd like to have happen.

import Ember from 'ember';

export default Ember.Service.extend({
    model: (function() {
        var data = [];

        var socket = io.connect('http://localhost:8080');

        socket.on('posts', function (data) {
            data = data.posts;
            console.log(data);
        });

        return data;
    })()
});

Is there a proper way to go about this?
Is this an app appropriate way to get data into a Service.
File Location app/services/posts.js





samedi 20 janvier 2018

'this' undefined only from component integration test

This is an Ember component that will need this at some point:

export default Component.extend({
  filteredSubs: computed.filter('model.subs', function() {
    // this will always return true in development http://localhost:4200/dummy
    // but will always return false in test because this === undefined
    return this;
  })
});

Dummy has a one-to-many relationship to Sub:

export default Model.extend({
  subs: hasMany('sub')
});

export default Model.extend({
  dummy: belongsTo('dummy')
});

This test fails but shouldn't:

test('it renders', function(assert) {
  let dummy = server.create('dummy');
  server.create('sub', { dummy });

  this.set('dummy', dummy);
  this.render(hbs``);

  assert.equal(this.$().text().trim(), 'Hi! There are 1 sub-dummies');
});

not ok 13 Chrome 63.0 - Integration | Component | show dummy: it renders

actual: Hi! There are 0 sub-dummies

expected: Hi! There are 1 sub-dummies




I am getting errors while installing ember add on ember-cli-tutorial-style,

enter image description here

below versions of node, npm and ember-cli i am using...

ember-cli: 2.18.0 node: 8.9.4 os: win32 ia32 npm : 5.6.0

please guide me how to address this kind of issues




Post data to Djnago rest API via emberJS in desired format

I have EmberJS using Django REST API, I have few checkboxes which I am using to filter the data based on selection of checkbox.

<label>Certificate</label>
<div>
    <div>
        <div class="form-group-checkbox">
            
            <label for="certificate_A">A</label>
        </div>
        <div class="form-group-checkbox">
            
            <label for="certificate_B">B</label>
        </div>
        <div class="form-group-checkbox">
            
            <label for="certificate_C">C</label>
        </div>                
    </div>
</div>

Currently I am getting below in querystring while calling the API:

.../Search?certificate_A=true&certificate_B=true

But the API needs string array for this parameter and it expects the parameter as mentioned below:

../Search?certification=certificate_A&certification=certificate_B

How can I modify the emberJS code to generate the API request in above shown format?




vendredi 19 janvier 2018

Using "ember new" missing package error

I use ember-cli to create a new Ember application. Command ember new my_app_name --skip-git

Encounter errors:

Error: 404 Not Found: @ember/test-helpers@^0.7.9

My version:

$ ember -v
ember-cli: 2.16.2
node: 4.7.0
os: linux x64




EmberJS as keyword in handlebars template

I have referred to the EmberJS official guide to understand the usage of "as" keyword in handlebars template. But I find it very confusing.

Could someone please explain me in easy terms (in relation to passing values to component, yield, etc)

Any examples would be really appreciated.




EmberJS: How to find which controller is used to drive .hbs view?

I have inherited a codebase and trying to make sense of what is what. In emberjs application how do I know which controller (js) corresponds to a view (hbs) on a particular page. Is there a setting? Is there a convention?




Pie is not a function in Ember D3 Pie Chart

I am currently struggling to create a pie chart in Ember using D3 as installed by the add-on ember-d3. To create the chart I am working backwords from a great example posted on git here.

With my current code I receiving an error in the console that 'pie' is not a function. The code is as follows:

import Ember from 'ember';
import Component from 'ember-component';
import {arc, pie} from 'd3-shape';
import { select } from 'd3-selection';
import { scaleOrdinal } from 'd3-scale';


export default Component.extend({

  radius() {
    let width = this.get('width'),
        height = this.get('height');

    return Math.min(width, height) / 2;
  },
  color() {
    return scaleOrdinal().range(['#A60F2B', '#648C85', '#B3F2C9', '#528C18', '#C3F25C'])
  },
  arc() {
    let radius = this.radius();
    return arc().outerRadius(radius - 10).innerRadius(0);
  },
  labelArc() {
    let radius = this.radius();
    return arc().outerRadius(radius - 40).innerRadius(radius - 40);
  },

  didInsertElement() {
    let data = this.get('data');
    this.pieChart(data);
  },

  pieChart(dataIn, dataIndexIn) {
    let width = this.get('width'),
        height = this.get('height'),
        arc = this.arc(),
        labelArc = this.labelArc(),
        color = this.color(),
        that = this;

    let data = dataIn;

    let pie = pie()
          .value(function(d) { return d.count; })(data[dataIndexIn]);

    let svg = select("#pie-chart")
          .append("svg")
          .attr("width", width)
          .attr("height", height)
          .append("g")
          .attr("transform", "translate(" + width/2 + ", " + height/2 + ")");

    let g = svg.selectAll("arc")
          .data(pie)
          .enter().append("g")
          .attr("class", "arc");

    g.append("path")
        .attr("d", arc)
        .style("fill", function(d, i) { return color(i); })
        .style("stroke", "#222")
        .each(function(d) { this._current = d; that.set('chartContext', this._current); });

    //Labels
    g.append("text")
        .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
        .text(function(d) { return d.data.color; })
        .attr("text-anchor", "middle")
        .style("fill", "#FFF")
        .each(function(d) { this._current = d; that.set('chartContextLable', this._current); });

  },

});

As far as I can tell d3-shape is being imported correctly as I do not receive an error about 'arc'. If I do remove 'arc' from the import statement I receive an error to say that 'arc' is not defined. This suggests the module is importing correctly.

The shape module also imports correctly on other component charts that do not use the pie function.

I think this suggests a syntax error but I can't see one.

Mock data is passed to the component via the controller and template helper:

data: [
  { label: 'Abulia', count: 10 },
  { label: 'Betelgeuse', count: 20 },
  { label: 'Cantaloupe', count: 30 },
  { label: 'Dijkstra', count: 40 }
],






jeudi 18 janvier 2018

Ember (Javascript) - how to signal the caller about the state of a promise

  • I have Ember code where the backend API calls are abstracted into a separate service. This service uses ember-ajax library for making backend calls.
  • This service sets up the common headers, handles the timeout errors, and 4xx/5xx errors. And anything else like 422 (validation errors) are left to be handled by the calling code.

-

 getCustomerProfile (authenticationToken) {
         const backendService = this.get('callBackendService');
         return backendService.callEndpoint(GET_METHOD,
             getCustomerProfileAPI.url,
             {'X-Auth-Token': authenticationToken}).then((customerProfileData) => {
                if (!backendService.get('didAnybodyWin') && customerProfileData) {
                   backendService.set('didAnybodyWin', true);
                   return customerProfileData.profiles[0];
                }
             }).catch((error) => {
                if (isInvalidError(error)) {
                   if (!backendService.get('didAnybodyWin')) {
                      backendService.set('didAnybodyWin', true);
                      backendService.transitionToErrorPage();
                      return;
                   }
                } 
          });
    }

and the call-backend-service looks like this

  callEndpoint (httpVerb, endPoint, headersParameter, data = {}, 
   timeoutInMillisecs = backendCallTimeoutInMilliseconds) {
    const headersConst = {
        'Content-Type': 'application/vnd.api+json',
        'Accept': 'application/vnd.api+json',
        'Brand': 'cibc'
    };
    var headers = Ember.assign(headersParameter, headersConst);

    var promiseFunctionWrapper;

    this.set('didAnybodyWin', false);
    if (httpVerb.toUpperCase() === GET_METHOD) {
        Ember.Logger.warn('hit GET Method');
        promiseFunctionWrapper = () => {
            return this.get('ajax').request(endPoint, {headers});
        };
    } else if (httpVerb.toUpperCase() === POST_METHOD) {
        Ember.Logger.warn('hit POST Method');
        promiseFunctionWrapper = () => {
            return this.get('ajax').post(endPoint, {data: data, headers: headers});
        };
    } 

    return RSVP.Promise.race([promiseFunctionWrapper(), this.delay(timeoutInMillisecs).then(() => {
        if (!this.get('didAnybodyWin')) {
            this.set('didAnybodyWin', true);
            Ember.Logger.error('timeout of %s happened when calling the endpoint %s', backendCallTimeoutInMilliseconds, endPoint);
            this.transitionToErrorPage();
            return;
        }
    })]).catch((error) => {
        if (!this.get('didAnybodyWin')) {
            if (isTimeoutError(error)) {
                this.set('didAnybodyWin', true);
                Ember.Logger.warn('callBackEndService: isTimeoutError(error) condition is true');
                this.transitionToErrorPage();
                return;
            } else if (isAjaxError(error) && !isInvalidError(error)) { //handles all errors except http 422 (inValid request) 
                    this.set('didAnybodyWin', true);
                    Ember.Logger.warn('callBackEndService: isAjaxError(error) && !isInvalidError(error) [[ non timeout error]] condition is true');
                    this.transitionToErrorPage();
                    return;

            } else {
                throw error;  // to be caught by the caller
            }
        }
    });
},

The callEndpoint does a RSVP.Promise.race call to make sure the called backend API comes back before a timeout happens. It runs two promises and whichever resolves first is the one that wins. didAnybodyWin is the flag that guards both the promises from getting executed.

Up to this part is all fine.

But this didAnybodyWin becomes the shared state of this call-backend-service because it has to convey back to the caller whether it ran the default set of then or catch blocks or does it expect the caller to run its then/catch blocks.

The problem is when model() hook is run, I am doing

RSVP.all {
  backendAPICall1(),
  backendAPICall2(),
  backendAPICAll3()
}

This RSVP.all is going to execute all 3 calls one after another, so they will hit the call-backend-service in an interleaved fashion and hence run the risk of stepping over each other (when it comes to the didAnybodyWin shared state).

How can this situation be avoided ? Is there any other better way for the callee to signal to the caller whether or not its supposed to do something with the returned promise.




Ember mirage introduce delay in specific cases only

To test some Timeout cases in my front-end, I want to introduce an artificial delay in mirage while responding to some specific requests only and respond right away for all other cases.

i am writing Mirage scenario like this

export default function () {
    this.post('/ebm-anp/api/v1/json/sessions', (schema, request) => {
  const req = JSON.parse(request.requestBody);
    if ((req.card.value === '12345678' || req.card.value === '12345678-encrypted-value') && req.password === 'abc') {
            return new Response(200, {'X-Auth-Token': '2704412f-7820-4431-86c1-1234567800'}, successResponse);
    }else if (..){

    }
  }
}  

In this post, Introduce momentary delays in ember-cli-mirage Sam suggested to use {timing: 400}; with the call , which when used in my example looks like following.

export default function () {
    this.post('/ebm-anp/api/v1/json/sessions', (schema, request) => {
  const req = JSON.parse(request.requestBody);
    if ((req.card.value === '12345678' || req.card.value === '12345678-encrypted-value') && req.password === 'abc') {
            return new Response(200, {'X-Auth-Token': '2704412f-7820-4431-86c1-1234567800'}, successResponse);
    }else if (..){

    }
  },{timing: 400};
} 

This basically introduces the delay in the calls for all testcases that hit this endpoint - which does not serve my purpose.

Is there someway i could refactor my Mirage setup so that i can setup the timing(delay) configuration only for some cases and leave it normal for all others.




Ember:Hook to execute code after model loads from any route?

% Preamble %

I am setting up ember-cli-sentry and am looking to identify the user so that when we get exceptions reported, we know what user those exceptions were associated with, in case they were user-specific. (Say, we deploy to staging, we got some data from the backend that was bad, causing certain errors with the only the users who got that bad data into their account).

& Actual question &

I want to execute some code immediately after the user model loads. I do not know what route is going to be triggering the user model to load.

In theory, actually, the earliest possible place I could get user model data is after the XHR for that data comes in over the network. I wonder, would it be crazy to hijack the XHR method, and when the user id is requested, run my code to tell raven/sentry who this user is?

It would be better if there was simply a "loaded" hook for model files, but I've never heard of such a thing. Maybe this is the one use case where this would be desirable?




In what order does Ember process events vs remove components?

I seem to be running into some subtleties around the order of DOM events firing and components being removed/destroyed that have me fairly confused. I'm trying to fix an issue with the ember-drag-drop library, where, if the draggable component is removed because of a change is made in the drop event handler, then the lib's drag coordinator service to be left in a weird state

full issue is here: https://github.com/mharris717/ember-drag-drop/issues/118

the gist of it is that the browser fires dragStart -> drop -> dragEnd, but Ember seems to be removing the component before the dragEnd handler has a chance to fire. To work around this, I added the cleanup to the willDestroyElement hook (only performed if the element is currently being dragged), which seems to work... except now, for some reason, after the cleanup is performed in willDestroyElement, the endDrag hook does (usually?) fire, resulting in cleanup being performed a second time, which in turn causes a backtracking render error.

I can work around this by adding some logic to only perform the cleanup if it hasn't yet been done, but would really like to understand why this is occurring

  MCVE that demonstrates the original problem is here: https://ember-twiddle.com/155776d5af6dd8b662fea9a914921329




Keeping subfolder in locale folder in emberjs

In my locales folder contains 2 folder now as :

en and ch ( english and chines ) works fine. But now I require to split the languages as by country. I prefer to keep the parent folder as country and sub folders as langue(s) like :

UK => En and UK => ch so, can i keep the no.of folder for according to their country and subfolders are no.of languages?

can any one help me to keep multiple counties with multiple languaes inside?

Thanks in advance.




mercredi 17 janvier 2018

Embed Ember app in existing Angular app?

Is there a way to embed Ember application in existing Angular application (or vice versa)?




Bar Height change following Y Axis inversion in D3 Charts

I have a Bar Chart component in my Ember application and the Y axis scaled incorrectly (it has the lowest count at the top and the highest at the bottom).

I can flip the Y axis by changing .range[ 0, barHeight ] to .range[ barheight, 0] but this distorts the bars so they no longer represent the correct values.

I know that the bar height needs to be changed but I am not sure how to do this within the component. Any help greatly appreciated:

Relevant Code:

 let svg = select(this.$('svg')[0]);
    this.set('svg', svg);
    let {
      width,
      height
    } = this.get('svg').node().getBoundingClientRect();

let padding = {
      top: 10,
      bottom: 30,
      left: 40,
      right: 0
    };

let barsHeight = height - padding.top - padding.bottom;
    this.set('barsHeight', barsHeight);

  // Y scale & axes
    let yScale = scaleLinear().range([ 0, barsHeight ]);
    this.set('yScale', yScale);
    this.set('yAxis', axisLeft(yScale));
    this.set('yAxisContainer', svg.append('g')
      .attr('class', 'axis axis--y')
      .attr('transform', `translate(${padding.left}, ${padding.top})`)
    );
 //Update the scales on chart render
this.get('yScale').domain([ Math.max(...counts), 0 ]);

//Update the Axis
  this.get('yAxis').scale(this.get('yScale'));
    this.get('yAxisContainer').call(this.get('yAxis'));

//drawing the bars

  barsEnter
      .merge(barsUpdate)
      .transition()
      .attr('width', `${this.get('xScale').bandwidth()}px`)
      .attr('height', data => `${this.get('yScale')(data.count)}px`)
      .attr('x', data => `${this.get('xScale')(data.label)}px`)
      .attr('y', data => `${this.get('barsHeight') - this.get('yScale')(data.count)}px`)
      .attr('fill', data => this.get('colorScale')(data.count))
      .attr('opacity', data => {
        let selected = this.get('selectedLabel');
        return (selected && data.label !== selected) ? '0.5' : '1.0';
      })




elem.getClientRects is not a function when clicked on filter icon

I have installed kendo grid in my ember app but once i click on excel export or filter icon i am getting this error in console.

jquery.js:9984 Uncaught TypeError: elem.getClientRects is not a function
    at kendoJQuery.fn.init.offset (jquery.js:9984)
    at init._position (kendo.all.js:14565)
    at init.open (kendo.all.js:14420)
    at init.toggle (kendo.all.js:14456)
    at init._click (kendo.all.js:35872)
    at HTMLAnchorElement.proxy (jquery.js:496)
    at HTMLAnchorElement.dispatch (jquery.js:5206)
    at HTMLAnchorElement.elemData.handle (jquery.js:5014)

how to resolve this issue?




How to request from URL that is not Ember.js-conform?

An unread count needs to be displayed in the navbar for our chat app. It can be requested under the following URL:

.../chats/get_unread_count

and the response is the following:

{
 "unread": 0
}

Since the URL is not conform to the Ember.js standard, I am unsure how to get Ember to request it under this URL. I ran out of ideas to try so I hope you can help me.




mardi 16 janvier 2018

emberjs | beforeModel hook is firing after model hook

I have a mixin with following definition.

import Ember from 'ember';

export default Ember.Mixin.create({

  loggedinUser: {},
  beforeModel() {  

    if (!this.get('AuthService').isAuthenticated()) {
       this.transitionTo('login');
    }

    this.get('AuthService').getLoggedinUser()
    .then(results => {this.loggedinUser = results;
      alert("in before model"); 
    alert(this.loggedinUser.requestorId);    
    });     
  } }
});

I import it in my route as following

import UnAuthenticatedRouteMixin from '../mixins/un-authenticated-route-mixin';

export default Ember.Route.extend(UnAuthenticatedRouteMixin, {

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

    alert("in model");
    alert(this.loggedinUser.requestorId); 

  }
});

My expected order of alerts is "in before model " -> "1234", "in model" , "1234". However the actual order of alerts is "in model " -> "undefined", "in before model" , "1234"

How can I ensure that beforeModel hook is fired after model hook.




Ember call method defined in mixin

I have the following code in my Ember app;

var FooMixin = Ember.Mixin.create({
  testMethod: function(){
    alert("FooMixin");
  }
});

App.IndexController = Ember.Controller.extend(FooMixin, {
   testMethod: function(){
     alert("IndexController"); // This alerts FooMixin if testMethod not defined in IndexController 
   },
  actions: {
    selectSomething: function(item) {
      this.testMethod();
    }
  }
});

So "testMethod" is defined in the mixin as well as IndexController which extends FooMixin. The action alerts "FooMixin" if testMethod is not defined in IndexController, else it alerts "IndexController"

My question is if this is the normal Javascript inheritance behavior. Anything else that I need to understand on how this thing works with mixin.




In ember, how can I correctly treat routes whose pathnames contain hashes (#) as fragment identifiers?

In my router I have the following block:

Router.map(function() {
  this.route('stuff');
  this.route('registration', { path: '/registration' });
  this.route('registration-first', { path: '/registration#first' });
});

The reason I wish to do this is so that from a user perspective, it makes logical sense that each route is a subsection or "fragment" of a single pipeline, but internally, I'm treating each page as a separate route because separation of concerns make more sense for my use case.

The approach above works perfectly fine except when I perform the following:

  • Transition to the hashed route
  • Return to the previous route/page (back button, browser)
  • Forward back to the hashed route/page

At this point in time the browser successfully adds the fragment identifier to the URL, but my route does not transition to the hashed route. Is there any way I can achieve this? Thanks.




Use of Ember.$.proxy

In my Ember app, I have the following code;

eventsToListen: function() {
    var self=this;
    return [{
        eventName: "Submit",
        callBack: Ember.$.proxy(this.clearFunction, this)
    }];
},

I wanted to understand what does the line "Ember.$.proxy" signify ?

Is that a jquery method ?




lundi 15 janvier 2018

Ember js 'ember build' error - Error: EBUSY: resource busy or locked, symlink

I have a existing quiet old ember.js project which I want to edit/mod. When running 'ember build' or 'ember serve' I get the error below. I read the other issues similar to this but none of the suggestion helped me so far. Can anyone please help how to solve this?

Output from ember version --verbose && npm --version: ember-cli: 2.5.1 http_parser: 2.7.0 node: 5.12.0 v8: 4.6.85.32 uv: 1.8.0 zlib: 1.2.8 ares: 1.10.1-DEV icu: 56.1 modules: 47 openssl: 1.0.2h os: win32 x64


Build failed.
The Broccoli Plugin: [BroccoliMergeTrees: Addon#treeFor (ember-data - addon)] fa
iled with:
Error: EBUSY: resource busy or locked, symlink 'C:\myprojectfolder\tmp\broccoli_merge_trees-output_path-z7GLec0z.tmp' -> 
'C:\myprojectfolder\tmp\broccoli_merge_trees-input_base_path-dgyw33ia.tmp\4'
    at Error (native)
    at Object.fs.symlinkSync (fs.js:945:18)
    at symlinkWindows (C:\myprojectfolder\node_modules\symlink-or-copy\index.js:123:18)
    at symlinkOrCopySync (C:\myprojectfolder\node_modules\symlink-or-copy\index.js:63:5)
    at C:\myprojectfolder\node_modules\broccoli-plugin\read_compat.js:86:11
    at tryCatch (C:\myprojectfolder\node_modules\rsvp\dist\rsvp.js:525:12)
    at invokeCallback (C:\myprojectfolder\node_modules\rsvp\dist\rsvp.js:538:13)
    at publish (C:\myprojectfolder\node_modules\rsvp\dist\rsvp.js:508:7)
    at flush (C:\myprojectfolder\node_modules\rsvp\dist\rsvp.js:2415:5)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)

The broccoli plugin was instantiated at:
    at BroccoliMergeTrees.Plugin (C:\myprojectfolder\node_modules\broccoli-plugin\index.js:7:31)
    at new BroccoliMergeTrees (C:\myprojectfolder\node_modules\broccoli-merge-trees\index.js:42:10)
    at BroccoliMergeTrees (C:\myprojectfolder\node_modules\broccoli-merge-trees\index.js:36:53)
    at mergeTrees (C:\myprojectfolder\node_modules\ember-cli\lib\models\addon.js:35:14)
    at Class.treeFor (C:\myprojectfolder\node_modules\ember-cli\lib\models\addon.js:300:10)
    at C:\myprojectfolder\node_modules\ember-cli\lib\broccoli\ember-app.js:463:20
    at Array.map (native)
    at EmberApp.addonTreesFor (C:\myprojectfolder\node_modules\ember-cli\lib\broccoli\ember-app.js:461:30)
    at EmberApp._addonTree (C:\myprojectfolder\node_modules\ember-cli\lib\broccoli\ember-app.js:871:36)
    at EmberApp._processedVendorTree (C:\myprojectfolder\node_modules\ember-cli\lib\broccoli\ember-app.js:916:20)




Changing color of link dynamically in emberJS

This is my app.hbs file, when i click the link it should be highlighted,Please help me how to do this.I am new to Ember and cannot find a clear solution to it. I am having ember version 2.18.

  MANUAL ADD </div>
  <br>
 
  CSV ADD
   




Calling Ember Model in Computed Property returns incorrect array

I'm trying to format data held in an Ember Model so that I can plug it into a Chart Component.

Route code:

import Route from '@ember/routing/route';
export default Route.extend({
  model() {
      let dateFrom = this.paramsFor('dashboard').dateFrom
      let dateTo = this.paramsFor('dashboard').dateTo
      let hash = {dateFrom, dateTo}
  return Ember.RSVP.hash({
    custakelist: this.get('store').query('custakelist', hash),
    barchart: this.get('store').query('barchart', hash),
      });
},

setupController(controller, models) {
  this._super(controller, models);
  controller.set('barchart', models.barchart);
  controller.set('custakelist', models.custakelist);
},

Controller Code:

import Controller from '@ember/controller';
import groupBy from 'ember-group-by';
export default Controller.extend({
  entriesByDate: groupBy('custakelist', 'take_list_date'),
  entriesByAge: groupBy('custakelist', 'patient_age'),

  wardData: Ember.computed.map('entriesByDate', function(group) {
      return {
      label: group.value,
      count: group.items.length
    };
  }),

  ageData: Ember.computed.map('entriesByAge', function(group) {
      return {
      label: group.value,
      count: group.items.length
    };
  }),

  clerkData: Ember.computed.map('barchart', function(barchart) {
      return {
      label: barchart.label,
      count: barchart.count
    };
  }),

});

I know that the models are being loaded on the page correctly thanks to Ember Data. I also know that the 'custakelist' model is being used by other charts.

When I try to use the model 'barchart' and log the result to the console I can see that an array with the correct number of items is created but they don't contain any values, they just display as follows:

0: {label: Computed Property, count: Computed Property}

How can I make the data that is already loaded as per my model usable in this context?




Ember-hifi how to set header to request

I try to use ember-hifi. It works grate from the local store. But i have troubles to play sound from server. My server demands auth header to be present. And the url looks like http://ift.tt/2Dbgr9f. When i send get request, the server return file that can be of mp3 or wav. But i do not know the format before get it. That way i get warning about mime type. But if hifi service try to get record from server the conection refused because there is no auth header in request. How to add header to requests from addon? I do not understand what options i can set to play method.




dimanche 14 janvier 2018

how to trigger a function automatically in ember.js action helper?

I am new to ember.js and working on an application to highlight text like below:

<div>
  <h3 class = "title" ></h3>
  <div class = "date" ></div>
  <p class = "content" >
  </p>
</div>

I created a function highlight which will get the class name and highlight the search text the user input. This function works fine, but I have to click to trigger this highlight function. Is there any way in ember action helper can trigger this function whenever the div node rendered or automatically triggered?




two-way data binding features of MVC JavaScript frameworks

When it is said that Angular/Ember or any other similar MVC JS framework features two-way data binding, keeping both view and model in sync for all the time.

Is it true that this feature has to be explicitly implemented with the help of Computed Properties (CP) i.e. a property say "fullName" can be kept in sync between model/view only if "fullName" is defined as a CP

Is that correct ? Any other way to implement this ?




samedi 13 janvier 2018

Is 'incrementProperty' an async call?

Looking at the Ember tutorial on testing models, it treats incrementProperty as an async call. Why?

app/models/player.js

import Model from 'ember-data/model';
import { attr } from 'ember-data/model';

export default Model.extend({
  level: attr('number', { defaultValue: 0 }),
  levelName: attr('string', { defaultValue: 'Noob' }),

  levelUp() {
    let newLevel = this.incrementProperty('level');
    if (newLevel === 5) {
      this.set('levelName', 'Professional');
    }
  }
});

tests/unit/models/player-test.js

import { moduleForModel, test } from 'ember-qunit';
import { run } from "@ember/runloop";

moduleForModel('player', 'Unit | Model | player', {
  // Specify the other units that are required for this test.
  needs: []
});

test('should increment level when told to', function(assert) {
  // this.subject aliases the createRecord method on the model
  const player = this.subject({ level: 4 });

  // wrap asynchronous call in run loop
  run(() => player.levelUp());

  assert.equal(player.get('level'), 5, 'level gets incremented');
  assert.equal(player.get('levelName'), 'Professional', 'new level is called professional');
});

The code appears to be synchronous as far as I can tell.




vendredi 12 janvier 2018

use prototype.js in ember application

hi and sorry for my english

It that possible to use prototype.js in Ember application. I want to migrate for test this framework but i dont need to make big change in code. all web page use scriptaculous




ember-api-actions collectionAction raise error Cannot read property 'constructor' of undefined

I have model mailbox with collectionAction

import DS from 'ember-data'
import { collectionAction } from 'ember-api-actions'

export default DS.Model.extend({
  mailbox: DS.attr(), //display only
  pin: DS.attr(),
  download: collectionAction({ path: 'greeting'})
})

and when i try to call download from my component i get an error

import Component from '@ember/component'
import Ember from 'ember'
import FileSaverMixin from 'ember-cli-file-saver/mixins/file-saver'

export default Component.extend(FileSaverMixin, {
  hifi: Ember.inject.service(),
  notifications: Ember.inject.service('notification-messages'),
  startPlay: true,
  changeset: {},
  actions: {
    toggle () {
      let hifi = this.get('hifi')
      if (this.get('startPlay')){
        this.set('startPlay', false )
        this.get('changeset').get('download')().then((content) => {
          this.saveFileAs(this.get('filename'), content, this.get('contentType'))
          })
        this.get('play')()
      } else {
        hifi.togglePause();
      }
    },
  }
})

The error is Uncaught TypeError: Cannot read property 'constructor' of undefined. I check my cod/ It is the same like ember-api-actions But my cod did not work. Please help me. I don't understand what is wrong.




Re-factoring D3 examples into Ember Components

I've recently started working with D3 and I have found that if I try and take some example code from places like Blockbuilder it is quite difficult to refactor it into a working Ember component.

I am using ember-d3 and understand that I need to import specific modules in the component.js file.

Taking an example like this:

  var vis = d3.select("svg")
        .append("svg:svg")   
        .data([data])                   
            .attr("width", w)           
            .attr("height", h)
        .append("svg:g")                
            .attr("transform", "translate(" + r + "," + r + ")")  

    var arc = d3.svg.arc()             
        .outerRadius(r);

    var pie = d3.layout.pie()        
        .value(function(d) { return d.value; });    

    var arcs = vis.selectAll("g.slice")    
        .data(pie)                         
        .enter()                          
            .append("svg:g")               
                .attr("class", "slice");  

        arcs.append("svg:path")
                .attr("fill", function(d, i) { return color(i); } ) 
                .attr("d", arc);                                  

        arcs.append("svg:text")                              
                .attr("transform", function(d) {                  

                d.innerRadius = 0;
                d.outerRadius = r;
                return "translate(" + arc.centroid(d) + ")";       
            })
            .attr("text-anchor", "middle")                         
            .text(function(d, i) { return data[i].label; });
}

The above is a simple pie chart but adding. I understand the function of most of the code but refactoring it into an Ember component produces errors ranging from Unexpected Tokens to reserved words errors

So assuming I have the component being called in the template with and the component template has an element being successfully drawn on the page, what steps do I need to take to draw the chart in Ember?

There are surprisingly few resources on D3 and Ember.




jeudi 11 janvier 2018

What is the difference between AngularJS, Ember.js?

as i want to learn more about JS ,can any one tell me What is the difference between AngularJS, Ember.js which one is better to use




Ember: How to determine which property changed in a multi-property observer

With something like the following how can I determine which of the three properties has changed without resorting to something tedious like printing out all the values each time, or creating three separate observers?

variableObserver: Ember.observer('variable.{name,value,type}', function() {

  // which property changed?

}),




Is it possible to use ESLint to lint Handlebars template?

I'm trying to write an ESLint plugin for Ember to check if the handlebars template together with javascript code has no issues.

To achieve that, I need to lint .js component code together with .hbs component template.

I don't have much experience with writing ESLint rules, but I guess all I need is to somehow turn those .hbs files into AST and then lint it as usually, but I don't know how to do that.

Are those AST produced by Js and Handlebars even compatible?




mercredi 10 janvier 2018

ember.js Sorting model in controller

ember.js version: 2.18.0

model:

export default DS.Model.extend({

  name: DS.attr('string'),
  description: DS.attr('string'),
  songs: DS.hasMany('song')
})

controller:

export default Controller.extend({
  sortBy: ['name:asc', 'description:asc'],
  sortedBands: computed.sort('model', 'sortBy')
}

ember gave me the following error:

Only string, number, symbol, boolean, null, undefined, and function are allowed as default properties ember/avoid-leaking-state-in-ember-objects




Increase request timeout in Ember server

When using my Ember application in the Ember server ("ember serve"), any request that takes over 1.00 minutes fails with a 502 error. However, when I build my app, and use my local Apache server, requests don't fail for several minutes.

How do I increase the request timeout in Ember server? I don't see any options anywhere to set this value, nor can I find any sort of documentation online.




Capture Paste Content in Ember 2.6

I have an Ember App (Ember 2.6) and I am trying to capture paste data before it is pasted into a input component. I have tried registering a custom event in my Ember App following the docs.

http://ift.tt/2FkSn10

Then in my component...

paste: function(event) {
    console.log(event.originalEvent.clipboardData.getData('text/plain'))
}

This returns an empty string when pasting "foo".

I also tried this with jquery...

$('.table').on('paste',function(event) {
  console.log(event.originalEvent.clipboardData.getData('text/plain'))
}

This also returns an empty string.

I have read other stack overflow answers surrounding this issue and haven't found a solution that works for me. I have tried...

event.clipboardData.getData('text/plain')
window.clipboardData..getData('text/plain')

For getData() I have also tried...

'text', and 'Text'

What do I do?




Soft delete records in Ember

I'm using the paranoia gem on my Rails backend to manage soft deletions of records, however calling destroyRecord() on the Ember model causes it to be marked as deleted, hiding it from the collection on the frontend. On a page refresh, the record re-appears since it actually still exists in the backed albeit with a deleted_at timestamp set.

What is the best way to handle this in Ember? I'd like to be able to call deleteRecord() and not have the deleted flag set, but only for this model.




How can i call a jsp page in tomcat server in ajax call from ember app

Am New to ember.Am given a task to do the below. I have a form in ember and after i click the submit button, the controller has ajax call to a page in tomcat server.i have given url with the tomcat port with webapp name and page. In what way i can do this?. Should i make change to the environment.js file?please help me in implementing the above.




mardi 9 janvier 2018

make an input field required in ember.js

I know there is a way in plain html to require the field have some kind of value. I believe it's 'input required'. However, I'm not sure how to accomplish this in ember using handlebars. I've tried this but it was unsuccessful:



Thanks in advance.




lundi 8 janvier 2018

Ember sending query params fails

I am trying to pass a param in my path. i try like this:

route.js

this.route`enter code here`('purchase', {path: '/purchase'}, function () {
        this.route('purchaseDetails');
        this.route('purchaseEdit', {path:'purchaseEdit?country='}); //showing in the URL
        this.route('purchaseReview');
        this.route('purchaseConfirmation');
      });

redirecting like :

this.transitionTo('purchase.purchaseEdit', "SG");

But not works. any one correct me please?




Serialize id in _id format with serializeId in Ember

In my response from server i have id attribute like 'id'. But to update record i need to send in request id like '_id'. I try to use serializeId serializeId method. My adapter looks like

import DS from 'ember-data'
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-
mixin'
import Ember from 'ember'
import Inflector from 'ember-inflector'

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
  authorizer: 'authorizer:token',
  pathForType (modelName) {
    let underscored = Ember.String.underscore(modelName)
    return Inflector.inflector.pluralize(underscored)
  }

}) and voicemail serializer

import ApplicationSerializer from './application'
import DS from 'ember-data'
import Ember from 'ember'

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
  primaryKey: 'id',
  attrs: {
    history: {embedded: 'always'}
  },
  serializeIntoHash (data, type, snapshot, options) {
    let root = Ember.String.decamelize(type.modelName)
    data[root] = this.serialize(snapshot, options)
  },
  serializeId (snapshot, json, primaryKey) {
    let id = snapshot.id
    json['_id'] = id
  }
})

But serializeId method did not called during serializing. And in my payload i still get id like 'is' instead '_id'. How to solve my issue?




dimanche 7 janvier 2018

Sending Multiple values from `model` to `template.hbs` - the ember way

I am looking the correct ember recommendation approach to group my data values before i send to template.

Because I have the data in 2 different arrays.

I don't want to keep no.of iterators across the app. so I would like to group the data within newly creating/created array or the correct way ember recommends. any one help me?

my model : ( sample )

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return {
        "data" : {
        "group" : [{"group":"newGroup"}, {"group":"oldGroup"}],
        "details" : [{"name":"arif","age":"3"},                 {"name":"afi","age":"2"}]
      }
    }
  }
});

my hbs : / - how to show this? by equal array value?/


    <li>  --  </li>

</ul>

Live Demo




ember js variable binding

Ember version: 2.18.0

URL: http://localhost:4200/bands/

/templates/bands.hbs


<button class="btn btn-primary btn-sm new-band-button" onclick=>Add</button>

/controllers/bands.js

export default Controller.extend({
  name: 'abc',

  actions: {
    createBand: function(){
      var name = this.get('name');
    }
  }
});

On startup, the input will have the value 'abc' as defined in the controller.

But in the action, the name returned is still 'abc' whatever I typed in.

Any thoughts?




ember js trigger actions on my route

current URL: http://localhost:4200/bands

router.js:

Router.map(function() {
    this.route('bands', function(){
        this.route('band', {path: ':slug'}, function(){
          this.route('songs');
          this.route('albums');
      });
    });
});

app/routes/bands.js

export default Route.extend({
    actions: {
      createBand: function(){
         this.get('controller').set('name', '');
      }
    }
});

app/templates/bands.hbs


<button class="btn btn-primary btn-sm new-band-button" >Add</button>

It looks like the createBand() function cannot be triggered. Am I missing anything?




EmberJS & Nginx - Routes return 404's

It seems like a simple problem but I cannot find any official information about how to fix it.

The problem: Deploying an EmberJS app to Nginx - all routes return 404's.

The root route / works just fine. However any route besides / fails & returns 404's. Here's how I have my nginx.conf setup:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    root /home/ivo/myapp;
    index index.html;
    location / {
        include /etc/nginx/mime.types;
        try_files $uri $uri/ /index.html?/$request_uri;
    }
    }
}

This config is largely based on the nginx.conf that comes with the Nginx Docker image, which I am using.

From what I understand about Nginx, the location / block should be handling my routes, but for some reason it is not.

As a side note, I am shocked that EmberJS does not have any documentation about this at all. I even tried their Nginx config from their deployment section and it too did not work - http://ift.tt/2D5E4wq




samedi 6 janvier 2018

Ember JS - internatatoinalization

Are there any examples, tutorials on how to use internationalisation in Ember JS apps ? I found this ember-i18n add-on, but the docs seem to be outdated and there are no examples in their Wiki. It seems a little bit strange this lack of documentation and resources on ember CLI and Ember JS sites about that compared for example Ruby on Rails.




Set model not consoled by JSON stringify - what is wrong?

I am setting some value to model like :

afterModel:function(model,transation){
        Ember.set(model, 'processedTrans', 'TechMahindra');
    },

when i require the value I used to get : model.get('processedTrans') - works fine. But in case if I do:

JSON.stringify(model) - I am not finding the value what i set in the afterModel method. what is the issue here? or do i require to add any additional stuff to get in json string? Really what i set is my models property?

any one help me to understand this?




How to integrate pretender into selenium functional tests of an Ember App?

I have an Ember application that our team built and we have written many automated selenium functional tests. Some of these tests cannot be currently automated because they require failures that are very hard to replicate consistently (such as device failure codes, etc). For these we would like to add fixture data returned with the correct error codes to test the UX display.

I added fetch-pretender and created a serveFixtures call:

import fixtures from './all';
const Pretender = require('fetch-pretender');

let server = null;

export default {
  serveFixtures(options) {
    console.log('serveFixtures called');
    server = new Pretender();

    fixtures.serve(server, options);
    server.get('/l18n/:file', server.passthrough);
    server.get('config/app.json', server.passthrough);

    // Add all other routes as passthrough by default
    server.get('/**', server.passthrough);
    //server.post('/**', server.passthrough);
    server.put('/**', server.passthrough);

    server.unhandledRequest = (verb, path, request) => {
      console.log(`--- Pretender unhandled request - ${verb} ${path} ${request}`);
    };

    server.passthroughRequest = (verb, path, request) => {
      console.log(`--- Pretender passthrough request - ${verb} ${path} ${request}`);
    };

    // console.log(server);
    return server;
  },
};

Basically I pass in the options for the error code that I want to return and it adds that fixture data to the return endpoint.

I can see in the tests that the server is set up correctly when the tests run but it never returns any fixture data and it also never hits any of the passthroughRequest code either.

My best guess is that the server exists in the code but is not actually present in the application itself. I have no idea on how to bridge that gap so I am hoping someone has done this before.

Please note that we do not use the Ember test frame work for our function tests but we do use it for unit tests and integration tests but for that we use a Sinon sandbox stub out and return fixture data or fetch-mock to mock the calls and return fixture data.

Our selenium set up uses the selenium standalone server. When we do component testing of other components, those teams can use a dummy app with pretender to mock calls which is why we want to reuse pretender if possible. However this is the main app that includes these components and we don't really want to add pretender to the builds if possible.




vendredi 5 janvier 2018

Architectural design of a Heroku application with Ember.js, Node.js and Express

I'm starting to implement a Heroku application based on Ember (frontend), Node and Express (backend).

I'm thinking to segregate the frontend and the backend in different apps. Both apps will be secured by Auth0.

What do you think about it? I'm on the right way?




ember aborts transition to route when loading model from jsonapi

I have a very basic ember application. It defines a route called "clock" and a model called "timezone".

models/timezone.js:

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  technicalName: DS.attr(),
  utcOffset: DS.attr()
});

routes/clock.js:

import Route from '@ember/routing/route';

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

The data is loaded from a rest api that returns data according to the json api specification. I am using an application adapter:

adapters/application.js:

import DS from 'ember-data';

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

The api returns the following data when calling http://localhost:3000/timezones :

{"data":
 [
  {
   "type":"timezones",
   "id":"1",
   "attributes": {
    "title":"Local Time",
    "technical-name":"alfa",
    "utc-offset":1
    }
   }
]}

However ember refuses to render the clock route:

Attempting URL transition to /clock
Transition #0: application: calling beforeModel 
Transition #0: application: calling deserialize hook
Transition #0: application: calling afterModel hook
Transition #0: clock: calling beforeModel hook
Transition #0: clock: calling deserialize hook
Transition #0: clock: transition was aborted

What am I missing here?




jeudi 4 janvier 2018

LOGOUT only works on Internet Explorer(11) when the Internet Explorer Developer Toolbar is visible

LOGOUT only works on Internet Explorer(11) when the Internet Explorer Developer Toolbar is visible it working fine with chrome i tried all options from here but its not working is anything wrong in code ? I AM USING Ember here is code

logoutPage(){
      let parts = document.location.href.split('/');
      let logOutUrl='/abc/unsecured/j_spring_logout'
      window.location =logOutUrl;
}

am calling above function from

<a id="session_Logout"  style="cursor: pointer;"></a>




thought on ember js productivity

I have been learning ember js because some giants in the company say it is awesome. But I have been dealing with command line to run the app, generate routes and models which apparently is not productive while ember js official website says it is for productivity. There might be IDE out there but in an enterprise environment I can't just download it and use it. If ember js people think it is productive to start from command line without offering a GUI IDE, they should not have allowed GUI on ember js app because GUI seems not productive in their eyes. Or is it actually that they are too stupid to code an IDE?




Testing if a record and it’s relations have been destroyed

I've created an Ember service with a method to destroy a record and it's related data (defined by relationships in the model).

This is my delete-user.js service.

import Promise from 'rsvp';
import Service, { inject as service } from '@ember/service';

export default Service.extend({
  store: service(),

  deleteUserAndAssociatedData(userRecord) {
    return userRecord.get('posts')
      .then(postRecords => this._deletePosts(postRecords))
      .then(() => userRecord.destroyRecord());
  },

  _deletePosts(postRecords) {
    return Promise
      .all(postRecords.invoke('destroyRecord'));
  }
});

My question is how am I supposed to test this functionality? I would like to verify that the user and it's posts have been marked as destroyed.

This is what I have so far in delete-user-test.js:

import { moduleFor, test } from 'ember-qunit';
import { run } from '@ember/runloop';
import { A } from '@ember/array';
import EmberObject from '@ember/object';

moduleFor('service:delete-user', 'Integration | Service | delete-user', {
  integration: true
});

let generateDummyUser = container => {
  const store = container.lookup('service:store');

  return run(() => {
    return store.createRecord('user', { name: 'Dummy User'});
  });
};

let generateDummyPost = container => {
  const store = container.lookup('service:store');

  return run(() => {
    return store.createRecord('post');
  });
};

test('it exists', function (assert) {
  let service = this.subject();
  assert.ok(service);
});

test('should delete the user', function (assert) {
  let service = this.subject();

  run(() => {
    const userRecord = generateDummyUser(this.container);
    service.deleteUserAndAssociatedData(userRecord);
    assert.equal(userRecord.get('isDeleted'), true, 'the user is deleted');
  });
});

test('should delete posts of the user', function (assert) {
  let service = this.subject();

  run(() => {
    const userRecord = generateDummyUser(this.container);
    const postRecord = generateDummyPost(this.container);
    userRecord.get('posts').pushObject(postRecord);

    return run(() => {
      service.deleteUserAndAssociatedData(userRecord);
      assert.equal(postRecord.get('isDeleted'), true, 'the post is deleted');
    })
  });
});

But the tests fail on the first assertion already with the following error:

Assertion Failed: calling set on destroyed object: .isSynced = false"

Is there anyone who can point me in the right direction? Maybe I should stub the adapter? Spy on the destroyRecord method? I'm not sure where to go from here.

Any help is very much appreciated!




Updating from Ember 1.8.1 to Ember 1.9 with Ember Starter Kit

I'm am currently updating an Ember app built with Ember Starter kit from Ember 1.8.1 to 1.9 and Handlebars 2.0. I’m trying to update successfully without having to refactor a lot of code - I’m hoping this is possible.

At the moment, I’m getting an error in the console which says ‘Error: Unknown template object: function’. From what I have read it is because I’m using a template compiler which only understands Handlebars 1.3. I’m currently using Gulp to compile my templates. I’ve moved from gulp-ember-templates to gulp-handlebars which states that I can compile my templates using a specific Handlebars version.

This is how my 'templates' gulp task looks like:

gulp.task('templates', function () {
    gulp.src(paths.dev.templates + '**/*.hbs')
    .pipe(handlebars({
        handlebars: require('handlebars')
    }))
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
        namespace: 'TM.TEMPLATES',
        noRedeclare: true,
    }))
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('public/app'))
});

..and my package.json has

  "devDependencies": {
    "handlebars": "^2.0.0"
  }

I've read that I may need to update the runtime version, but I don't know where I can do this so I assumed if I installed the latest ember-template-compiler from NPM and referenced it in my gulpfile like below

//COMPILE ALL PULGIN FILES
gulp.task("all", function(){
    return gulp.src([
            paths.dev.vendor + "jquery/dist/jquery.js",
            paths.dev.vendor + "handlebars/handlebars.js",
            "/node_modules/ember-template-compiler/lib/main.js",
            paths.dev.vendor + "ember/ember.js", 
        ])
        .pipe(concat("all.js"))
        .pipe(gulp.dest("public/js/"));  
});

...it would work.

Unfortunately, I'm still getting ‘Error: Unknown template object: function’. I understand I could try and migrate the app over to Ember CLI there is no capacity for this at the moment.

Thanks.




mercredi 3 janvier 2018

Not able to update the model in `afterModel`

In existing model, I am trying to add some values in it in the afterModel hook. But I am not finding in the model at all. How to do this?

here is my try :

afterModel:function(model,transition){

        var that = this;
        let trans = Ember.A();

        model.get('ccList').forEach(function(card,num){

            let cname = card.get('cardName');
            let numb = card.get('cardNum');

            card.get('cardtransactions').map(function(transaction){
//adding some values
                transaction.set('cardName', cname );
                transaction.set('cardNum', numb );
                transaction.set('selected', false );
                transaction.set('handlingFee', "" );

                trans.push( transaction );

            });
        });

        model.set('processedTrans',trans); //assigning back 

        console.log( JSON.stringify( model.get('processedTrans').get('firstObject'))); //but not getting here

    },