mercredi 31 octobre 2018

Ember does not update value of based on another property

Hi i have a simple code that updates a component's property value e.g. with a button click, and based on that value i need to update the value of the input text, like so:

template:
<button>update</button>

component.js:
myValue: Ember.computed("product", function(){ if(this.get("product")) { return this.get("product"); } }),

But although, the "product" property is updated , the input value stays the same, computed function is not triggered.

Am i missing anything?




Rails API - how to enable ActiveStorage::DirectUploadsController

I'm using Rails API (5.2.0) and hit a problem when uploading a file directly from an Ember app by posting to ActiveStorage::DirectUploadsController#create (/rails/active_storage/direct_uploads path). I'm getting 404error. Does it means that the above controller is just not availabe in Rails API-mode app ? If so, how is it possible to include the corresponding module ? Or I'll have to create a custom controller inheriting from ActiveStorage::DirectUploadsController?

I created DirectUploadsController extending ActiveStorage::DirectUploadsControlleras follows:

class DirectUploadsController < ActiveStorage::DirectUploadsController
  protect_from_forgery with: :exception
  skip_before_action :verify_authenticity_token
end

And defined Post model:

class Post < ApplicationRecord
  serialize :tag_ids, Array
  validates :title, :body, :tag_ids, presence: true

  has_one_attached :photo
end

PostsSerializer looks like that:

class PostSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attributes :id, :title, :body, :tag_ids, :archived, :photo

  def photo
    url_for(object.photo) if object.photo.attached?
  end
end

When checking if a photo was attached to the Post, it seems to be OK:

2.5.0 :001 > post = Post.first
  Post Load (0.1ms)  SELECT  "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT ?  [["LIMIT", 1]]
 => #<Post id: 28, title: "post-1", body: "azertyui", tag_ids: [12], archived: true, created_at: "2018-10-31 15:26:49", updated_at: "2018-10-31 15:26:49"> 
2.5.0 :002 > post.photo.attached?
  ActiveStorage::Attachment Load (0.2ms)  SELECT  "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ?  [["record_id", 28], ["record_type", "Post"], ["name", "photo"], ["LIMIT", 1]]
  ActiveStorage::Blob Load (0.1ms)  SELECT  "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ?  [["id", 9], ["LIMIT", 1]]
 => true 

But when trying to display it in the front-end app on posts/index page it fails with errors:

Started GET "/posts" for 127.0.0.1 at 2018-10-31 17:13:20 +0100
   (0.1ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  ↳ /Users/Serguei/.rvm/gems/ruby-2.5.0/gems/activerecord-5.2.0/lib/active_record/log_subscriber.rb:98
Processing by PostsController#index as JSONAPI
  Post Load (0.1ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/posts_controller.rb:8
[active_model_serializers]   ActiveStorage::Attachment Load (0.2ms)  SELECT  "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ?  [["record_id", 28], ["record_type", "Post"], ["name", "photo"], ["LIMIT", 1]]
[active_model_serializers]   ↳ app/serializers/post_serializer.rb:7
[active_model_serializers]   ActiveStorage::Blob Load (0.1ms)  SELECT  "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ?  [["id", 9], ["LIMIT", 1]]
[active_model_serializers]   ↳ app/serializers/post_serializer.rb:7
[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::JsonApi (30.88ms)
Completed 500 Internal Server Error in 45ms (ActiveRecord: 2.2ms)



ArgumentError (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true):

app/serializers/post_serializer.rb:7:in `photo'
app/controllers/posts_controller.rb:8:in `index'

Where should I set those options ? :host parameter, set default_url_options[:host], or set :only_path to true

I created two repos to reproduce the problem:

  1. Rails API app
  2. Ember App (front-end client)



Ember: How can I pass multiple parameters to route through params

//router.js

Router.map(function(){
    this.route('posts');
    this.route('profile' { path: '/profile/:id1/:id2' });
});

I want to pass two id's to the profile route some how. Is that possible? tell me a solution to do it. also tell how should I set the profile/route.js file

Thanks in advance




Use Rails API with ActiveStorage DirectUpload and Ember JS

Rails guides explain how to use ActiveStorage with other libraries. I wonder how a separate Ember App can figure out of existence of DirectUpload class from activestorage ?




Is there any way to list google drive files and folder in my application using ember js

I want to create an application using Ember JS.Function of my application is to list all files and folders which present in my google drive to my application. I only have basic knowledge in ember js. Is there any way to implement my project using ember?




mardi 30 octobre 2018

Modifying POST url in Ember JS

Can you please explain how to use urlForCreateRecord in adapter to change the post url? I have two model employee and tasks with one to many relationship.

//Employee model
import DS from 'ember-data';

export default DS.Model.extend({
    empId : DS.attr(),
    password : DS.attr(),
    email : DS.attr(),
    tasks : DS.hasMany('task')
});

//Task model
import DS from 'ember-data';

export default DS.Model.extend({
    name : DS.attr(),
    description : DS.attr(),
    startDate : DS.attr(),
    endDate : DS.attr(),
    employee : DS.belongsTo("employee")
});

Now I want to create a task record. I am creating task record like this

let self=this;
let employee=this.store.peekRecord("employee",1);
let task=this.store.createRecord("task",{
    name:self.get("name"),
    description:self.get("description"),
    startDate:self.get("startDate"),
    endDate:self.get("endDate"),
    employee:employee
});
task.save();

The post request should go to URL like /employee/:employee_id/tasks. But the url is getting created like /tasks. How do I achieve the required post url?




How would I filter using filterBy for a multiple values selected and use mapBy to manipulate the array?

on my template I do have a dropdown that may select a multiple values Example, zoneNameOne, zoneNameTwo. My component.js has a code that would filter a records based on the multiple values that had been selected from the dropdown.

jobOrderCityNames: computed('selectedZoneOrCityName', 
 'jobOrders.@each.zoneName', 'jobOrders.@each.cityName', function() {
  let selectedZoneOrCityName = this.get('selectedZoneOrCityName');
  if (selectedZoneOrCityName) {
    return this.get('jobOrders').filterBy('zoneName', selectedZoneOrCityName).mapBy('cityName');
   } else {
    return [];
  }
}),

The jobOrders return a array of objects below. [{id: 123, type: "job-orders",…}, {id: 124, type: "job-orders",…}]

My problem: I can't filter the array of objects on a multiple values selected from the dropdown. Please see the code above

My question: How can I filter the array of objects on a multiple values and mapBy the property name?

Please help me, any response is much appreciated.




How to make a POST route in Emberjs

i have an ember application and backend api backend api needs to send data of the ember application using redirect and data should be sent over POST method.

this works with GET method with query params but how to acheive this with POST

if i explain futhermore,

let say there is url called www.webapp.com/user which user is defined in ember route as

 this.route('user');

if the backend redirect to https://ift.tt/2P0p10x i can capture it via user route of emberapp

but i neeed to send those params as POST params. when a POST redirect is made by server it cannot get captured from Ember routes.




Find number of records in the Returning model, in Ember js

// model

export default DS.Model.extend({
    name: attr('string'),
    owner: belongsTo('user'),
    num: attr('number'),
});

// route

export default Route.extend({
    model: function(){
        return this.store.query('post',{
            owner: 1
        });
    }
});

I want to know the number of records in the returning model ie.,it returns

{
       "name":"test1",
       "owner": 1,
       "num": 5
   },
   {
       "name":"test2",
       "owner": 1,
       "num",7
   },
   {
       "name":"test3",
       "owner": 1,
       "num": 2
   }

I want to get the value 3 as it has 3 records




Simple Ember Data Issue with Mirage

I have some experience with Ember.js, and am now going through creating a new project, with Mirage to stub the data for now.

I'm going through the Ember.js Tutorial step by step but keep getting this error when querying for records:

Encountered a resource object with an undefined type (resolved resource using DS.JSONAPISerializer)

I do realize that a similar question has been asked, but it did not include the Mirage addon, and I also went through all of the techniques answered in that question.


mirage/config.js

export default function() {
  this.namespace = '/api'

  this.get('/todos', function() {
    return {
      data: [
        {
          text: 'Bring in garbage cans',
          completed: false,
          timesViewed: 3
        },
        {
          text: 'Look at the plants',
          completed: false,
          timesViewed: 0
        }
      ]
    }
  })
}


app/models/todo.js

import DS from 'ember-data';

export default DS.Model.extend({
    text: DS.attr(),
    completed: DS.attr(),
    timesViewed: DS.attr()
});


app/routes/index.js

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

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


app/adapters/application.js

import DS from 'ember-data';

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


I've been formatting the response from Mirage in all kinds of ways, even doing the double quotes on keys, but that shouldn't be necessary since I believe mirage serializes it.

Any help on what I'm missing here is appreciated.




How to enable a component's property when i transitionToRoute

Hello i have a search component on page header.
When i click on a magnifyng glass, a flag property is getting true, so the search-box component is displayed like so:

enter image description here

When i press Enter on the magnifying glass i call an action, which, inside the application/controller.js it makes a redirection to a result-page, like so:

`actions: {
updateQuery(query) {
  return this.transitionToRoute('search-results', {
    queryParams: {
      query
    }
  })
 }
}

The redirections works as expected and the results-page loads, but the search-box component is still displayed! I havent found a way to disable the property flag , that it is inside the header component, yet.

Any ideas how to trigger that, when i do the redirection ?




ember, The id X has already been used with another record for modelClass

i have issues managing the deleted items in my Ember 2.18 store.

i have a "folder" model in my ember app (made with ember cli). i create a folder named "FOLDER1". I delete it, calling destroyRecord. then after successfully destroying, i do a store.unloadRecord(myFolder) in the promise. It calls my backend to delete it and updates the data store normally. The view updates accordingly, my folder seems to be deleted.

I can see the model is not present anymore in my Ember debug addon too, in Firefox, like expected.

But when i want to create an other folder named "FOLDER1", the ember data store throws this error

"The id FOLDER1 has already been used with another record for modelClass" from error.js.

like if it were not deleted. (And the ember addon kind of crashes, in the data tab, i have the list of my models, counting my folders but cannot view the content of these models when i click on it.)

Did i miss something in the deletion process, should i do something else ?




How to exclude a specific div on 'focus-out' event

I work on an Ember application, where i have :
1.
2. <div class="mylist"><u><li action >item</li></ul></div>

My problem is that when i click on an <li> item, the inputFocusOut function s executed.

Currently i have setTimeout inside the inputFocusOut to make it work.

But is there a way to exclude <div class="mylist"> when the focus-out event is triggered ? So not to be executed when i click on the <li>s , maybe?




Ember simple auth how to update when authenticate data is avaiable

Ember app is using adfs login. when a successful login adfs will redirect to ember web app with a route and query parameters. those query parameters contain

access_token
refresh_token
user_id
scope

i need to update session of the ember auth with those credential data. how can i achieve this ?




Ember Adapter Receive Data via Ajax Post

I am new to Ember and this is my first question on stackoverflow. I am working on client side of an Ember project and I need to pull JSON data from a Rest Api. Previously I could extract data given as below:

//app\adapters\product.js

export default DS.RESTAdapter.extend({

host:"http://10.1.7.13,
pathForType(){
 return "content.php?method=list&pr1=product&pr2=all&uname=aaa&upass=1234";    }});

// app\serializers\product.js

export default DS.RESTSerializer.extend({

normalizeResponse (store, primaryModelClass, payload, id, requestType){

payload={
    products:payload
};
return this._super(store,primaryModelClass, payload, id, requestType)

} });

Then the url for backend changed and now username and userpassword are not params for url but send in as form data.

In the new form the url for list products is "http://10.1.7.13/content.php?method=list&pr1=product&pr2=all"

Although if I just access with this url page gives warning as username and userpassword is not defined. So I cant reach json data.

But if I send an ajax post request as below

 $.ajax({

    type:"POST",

    url: "http://10.1.7.13/content.php?method=list&pr1=product&pr2=all",

    data: {
    "uname":"aaa",
    "upass":1234
    },

    success: function(response){

    console.log(response);
    }
});

I can see my JSON data as I have given username and password as form data. My question is where can I call this ajax post and how can I load the response to product model? Ideally I want to call on adapter and send response to serializer then add that to my model like before. But I looked into adapter methods and did not see one that helps me. I am new to rest api so could you tell me what should I do?




lundi 29 octobre 2018

Ember JS: How to import Material Components Web JS

I'm trying to use Material Components Web(MDC-Web) with an EmberJS application. I've installed material-componants-web with Yarn.

I have the sass/CSS working but can't figure out how to include/import the JS. Could someone show me how it would import that into my component js file and/or my component template file.

I get an no file error when I do an app.import('node_modules/material-components-web/dist/material-components-web.js').

Thanks for any help!




How to use a thenable with a computer property in Ember?

What is the correct way to use a thenable as one of the dependent keys of a computed property in Ember in 2018?

I would like the computed property to update when the promise/thenable resolves without jumping through hoops. I do this:

payableId: computed('paymentRecord.isSettled', function() {
  let paymentRecord = this.get('paymentRecord');
  if (paymentRecord.get('isSettled') === false) return;
  if (paymentRecord.content) paymentRecord = paymentRecord.content;

  return paymentRecord.belongsTo('payable').id();
}),

In my example, I have a paymentRecord which belongs to a payable and I want to get some information about the payable but the paymentRecord is not resolved until some unknown point in the future. The paymentRecord my or may not be a thenable so we have to jump through various hoops:

  • Have to be careful to check isSettled against false since undefined would indicate not a thenable
  • Have to drill down into .content if it exists in the case of a thenable

But it feels like a hack and I can't find anything about this in the guides.




Ember cannot display belongsTo value in template

I have 2 models set up with a one to one relationship.

models/character.js:

export default DS.Model.extend(Validations, {
    name: DS.attr('string');
    weapons: DS.belongsTo('weapon', {async:true}).
});

models/weapon.js

 export default DS.Model.extend(Validations, {
     weapon: DS.attr('string'),
     character: DS.belongsTo('character',  {async: true}),
 });

I create a newCharacter record, and set the weapon property in my controller like so:

let weaponChoice = this.get('weaponSelected');

    //find weapon based on weapon name
    let weaponPromise = this.store.query('weapon', {
        filter: {
            weapon: weaponChoice
        }
    }).then( (items) => {
        //set the weapon record here
        newCharacter.set('weapon', items.get('firstObject'));
        newCharacter.save();
    });

Then on a different page I try to display the weapon in my template like this:



When this displays It shows as:

<(unknown):ember300>

When I look at the ember tab in my console this makes sense because this is what it shows. However, when I look at my DB it shows that the weapon column has the id to reference the correct weapon.

The weapon is getting saved in my DB, but I cant seem to be able to properly access it when I want to display it on the page. How can I get access to it? Even when I give access to the weapon model in my route it still displays the same thing. Can anybody enlighten me as to what I am doing wrong?

Here is my route currently for reference:

export default Route.extend({
    model: function (params) {
        return this.store.findRecord('character', params.character_id);
    }
});




Ember 3, DataTable render buttons with actions

I'm migrating my app from Ember 1 to 3. It is using DataTables plugin for $JQuery with custom render method to show buttons dispatching controller's actions.

Now, my problem is that the older version of Ember allowed me to do kind of this (myController.js):

var dataTablesColumns = [
  .
  .
  .
  {
    mRender: function(data, type, row) {
      return `<button onclick="getView($(this)).parentController.send('myAction')`
    }
  }
]

Since Ember 3 does not support views anymore this approach is not working. How can I call controller's myAction using the dataTables in this way?

I've tried:

onclick="this.parentController.send('myAction')"
onclick="this.send('myAction')"

But nothing works. this refers to the button in the context not to the controller.

Thank you for any suggestion or help!




Major Ember upgrade - 1.12 to 3.5

In nearest future I will be doing a serious update of the application. I am not very familiar with ember.js & have no one who can help me with this material. The app is written in ember 1.12, and there are few dependencies. It has a web version and mobile (iOS+Android) written in cordova - all of them need an upgrade.

What kind of problems should I expect? How to prepare for them? How much time should I estimate? Any help will be very useful- it's first time when I will be doing app upgrade.

I have checked this links, but most of them are for above 2.0 versions.

https://www.emberscreencasts.com/meta_guide_to_upgrading_ember https://medium.com/ingenious/how-to-upgrade-ember-js-to-3-x-and-live-to-fight-another-day-cfc28c16b726 http://www.ember-cli-diff.org/ https://medium.com/front-end-hacking/everything-you-need-to-know-to-upgrade-your-ember-js-app-including-ember-3-9de5e808dde0 https://medium.com/ember-ish/upgrading-ember-from-1-13-to-2-8-0-f1dbcecc40ca https://medium.com/front-end-hacking/how-to-use-ember-2-code-in-your-ember-3-app-9ed15c28bad6




Error while processing route: leads str is undefined DECAMELIZE_CACHE (EmberJS)

I am trying to store data from the payload into a model using EmberJS, so that I can later display it in the table. However, when I run the application this is the error i get:

Error while processing route: leads str is undefined DECAMELIZE_CACHE<@http://localhost:4200/assets/vendor.js:17268:9
get@http://localhost:4200/assets/vendor.js:53750:39
decamelize@http://localhost:4200/assets/vendor.js:17361:16
STRING_DASHERIZE_CACHE<@http://localhost:4200/assets/vendor.js:17226:16
get@http://localhost:4200/assets/vendor.js:53750:39
dasherize@http://localhost:4200/assets/vendor.js:17380:16
normalizeModelName@http://localhost:4200/assets/vendor.js:64782:12
modelNameFromPayloadKey@http://localhost:4200/assets/vendor.js:80398:48
_extractType@http://localhost:4200/assets/vendor.js:80384:14
normalize@http://localhost:4200/assets/vendor.js:80425:15
_normalizePolymorphicRecord@http://localhost:4200/assets/vendor.js:82138:14
_normalizeArray/<@http://localhost:4200/assets/vendor.js:82112:34
_normalizeArray@http://localhost:4200/assets/vendor.js:82111:34
_normalizeResponse@http://localhost:4200/assets/vendor.js:82238:34
normalizeArrayResponse@http://localhost:4200/assets/vendor.js:81015:14
normalizeFindAllResponse@http://localhost:4200/assets/vendor.js:80875:14
normalizeResponse@http://localhost:4200/assets/vendor.js:80818:18
normalizeResponse@http://localhost:4200/assets/ember-sugar.js:347:14
superWrapper@http://localhost:4200/assets/vendor.js:53473:23
normalizeResponseHelper@http://localhost:4200/assets/vendor.js:70266:30
_findAll/<@http://localhost:4200/assets/vendor.js:70581:21
tryCatcher@http://localhost:4200/assets/vendor.js:59477:14
invokeCallback@http://localhost:4200/assets/vendor.js:59649:15
publish@http://localhost:4200/assets/vendor.js:59635:9
@http://localhost:4200/assets/vendor.js:51876:16
invoke@http://localhost:4200/assets/vendor.js:27556:17
flush@http://localhost:4200/assets/vendor.js:27476:25
flush@http://localhost:4200/assets/vendor.js:27635:25
_end@http://localhost:4200/assets/vendor.js:28057:26
end@http://localhost:4200/assets/vendor.js:27822:13
_run@http://localhost:4200/assets/vendor.js:28102:21
_join@http://localhost:4200/assets/vendor.js:28078:24
join@http://localhost:4200/assets/vendor.js:27876:20
join@http://localhost:4200/assets/vendor.js:16517:12
ajax/</hash.success@http://localhost:4200/assets/vendor.js:79042:11
fire@http://localhost:4200/assets/vendor.js:3609:11
fireWith@http://localhost:4200/assets/vendor.js:3739:7
done@http://localhost:4200/assets/vendor.js:9646:5
callback/<@http://localhost:4200/assets/vendor.js:9889:9

I have tried to google the solution as well as check if there is anything related to this on stack overflow, but to no avail. What seems to be the problem? I have even logged the data and it shows the payload correctly but somehow right after that the error pops up.

adapters/generic.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host: "http://localhost/SugarPro-Full-8.0.0",
  namespace: "rest/v10",
  headers: Ember.computed(function() {
    return {
      'oauth-token': sessionStorage.getItem('token'),
      'Content-Type': 'application/json'
    }
  })
});

adapters/lead.js

import generic from './generic' 

export default generic.extend({
  pathForType(){
    return 'Leads'; 
  }
});

models/lead.js

import DS from 'ember-data';

export default DS.Model.extend({
  records: DS.hasMany('record')
});

models/record.js

import DS from 'ember-data';
export default DS.Model.extend({
  name: DS.attr('string'),
  status: DS.attr('string'),
  account_name: DS.attr('string'),
  phone_work: DS.attr('string'),
  date_entered: DS.attr('string'),
  date_modified: DS.attr('string')
});

routes/leads.js

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

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

serializers/lead.js

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

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    records: { embedded: 'always' }
  },
  normalizeResponse(store, primaryModelClass, payload, id, requestType){
    payload = {records:payload}
    console.log(payload);
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

Many thanks for bearing with me and for your help in advance!




how to create a single sign on with emberjs 2.18

I want to login through a single sign on adfs page to ember app. to do that i have a localhost/login page which has a button. button click should leads to adfs login page (eg: adfs/sso/login ) and after success login i should able to login in to ember app.

im using ember-simple-auth to achive jwt token based login.

i have no clue how to achive this in emberjs

I know that there is an option of torii but i dont need to use a popup or an iframe to achive this




dimanche 28 octobre 2018

Ember QUnit - Is there a way to remove the stacktrace from failed assertions?

Every failed assertion looks like this

Integration | Component | x-form/x-radio-set: it should show errors if validations fail
    ✘ assert.equal(this.$('span').text().trim(), 'is too short (minimum is 4 characters)') at dummy/tests/integration/components/x-form/x-radio-set-test.js:87:4
            at Object.<anonymous> (http://localhost:7357/assets/tests.js:827:10)
            at runTest (http://localhost:7357/assets/test-support.js:4108:30)
            at Test.run (http://localhost:7357/assets/test-support.js:4094:6)
            at http://localhost:7357/assets/test-support.js:4300:12
            at Object.advance (http://localhost:7357/assets/test-support.js:3746:26)
            at begin (http://localhost:7357/assets/test-support.js:5567:20)
         expected is too short (minimum is 4 characters)

Which bloats the screen with pretty much useless information.

I'm expecting to have something like this:

Integration | Component | x-form/x-radio-set: it should show errors if validations fail
    ✘ assert.equal(this.$('span').text().trim(), 'is too short (minimum is 4 characters)') at dummy/tests/integration/components/x-form/x-radio-set-test.js:87:4
         expected is too short (minimum is 4 characters)


I'm also using ember-qunit-nice-errors which improves a bit the default assertion messages.




samedi 27 octobre 2018

Ember engines and common child dependencies

I have a very basic question regarding dependencies in an Ember app.

So say I have a parent application/engine called P1. This parent has multiple child apps/engines called C1, C2, C3. Now, the parent app as well as the child engines themselves have a common dependency on some library say L1. (This can be say jquery library) However, the version which say C1 defines as dependency is L1@1.0.0, while the parent P1 defines it as L1@2.0.0

My question is what dependency version would child C1 run with (1.0.0 or 2.0.0) ? Would it clash with same dependencies (but different versions) defined in other child engines ?

Dependency code can include JS as well as CSS. How does these resolve within the context of child apps ? Any examples for reference would really help.




vendredi 26 octobre 2018

404 throws a path that does not exist EmberJS

I was developing an ember application, which returns a payload to the application using rest, but when I run the application, it throws the following error:

Error: Ember Data Request GET /leads-mains returned a 404
Payload (text/html; charset=utf-8)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /leads-mains</pre>
</body>
</html>

The funny thing is, there does not even exist anything called leads-mains in my application! I wrote leads-main or lead-main everywhere in the code, and the path where it should check is Leads not /leads-mains, which I defined in my adapter clearly. Where is this coming from? How do I get rid of it?




prerender.io not working with ember app in dployment

i have this ember app which i wanna render it's SEO for search engines. i am using prerender.io for this purpose, this is the website https://thesmilestylist.ca . I am using apache midllware used apache middlware link. also my .htaccess file is

Header set test1 "test1"
<IfModule mod_headers.c>
Header set test2 "test2"
RequestHeader set X-Prerender-Token "xxxxxxxxxxxx"
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
Header set test3 "test3"
RewriteCond %{HTTP_HOST} ^www\.thesmilestylist\.ca [NC]
RewriteRule ^(.*)$ https://thesmilestylist.ca/$1 [L,R=301]

<IfModule mod_proxy_http.c>
Header set test4 "test4"
RewriteCond %{HTTP_USER_AGENT} googlebot|bingbot|yandex|baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator [NC,OR]
RewriteCond %{QUERY_STRING} _escaped_fragment_

# Only proxy the request to Prerender if its a request for HTML
RewriteRule ^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent|\.ttf|\.woff))(.*) http://service.prerender.io/https://thesmilestylist.ca/$2 [P,L]
</IfModule>
Header set test5 "test5"
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

</IfModule>

the search engines bots fetching correctly the website and it appears on my prerender.io crawl states but search engines still can't see the content of the pages after rendered. and my ember index.html is as follows

<!-- Use HTML5 doctype --> <!DOCTYPE html> <!-- Set locale language -->
<html lang="en-ca">
   <head>
      <!-- Plug favicon -->
      <link rel="icon" href="/inc/favicon.png" type="image/png" />
      <meta name="fragment" content="!"> 
      <!-- META[ -->
            <title>Oakville Cosmetic Dentistry - The Smile Stylist</title>
      <meta name="description" content="Call Now! (647) 478-9055 – The Smile Stylist cosmetic dentistry clinic, located in Oakville, ON specializes in porcelain veneers, dental implants & smile makeovers. Dr. Kaloti is renowned for crafting unforgettable smiles." />
      <meta name="keywords" content="full mouth reconstruction dentists, dentistry, porcelain veneers, dental clinics, oakville, toronto, gaps between the teeth, teeth whitening oakville, teeth whitening dental clinics oakville, cosmetic dental clinics, cosmetic dental clinics oakville, cosmetic dental clinics mississauga" />
          
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <!-- ]META --> <!--ASSETS[-->
      <link rel="stylesheet" href="/assets/vendor.css">
      <link rel="stylesheet" href="/assets/tsse.css">
      <!--]ASSETS--> <!-- Yandex.Metrika counter --> <script type="text/javascript" > (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter48714452 = new Ya.Metrika({ id:48714452, clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script>
      <noscript>
         <div><img src="https://mc.yandex.ru/watch/48714452" style="position:absolute; left:-9999px;" alt="" /></div>
      </noscript>
      <!-- /Yandex.Metrika counter --> <!--Google Analytics--> <script> (function ( i, s, o, g, r, a, m ) { i['GoogleAnalyticsObject'] = r i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date() a = s.createElement(o), m = s.getElementsByTagName(o)[0] a.async = 1 a.src = g m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga') ga('create', 'UA-115285690-1', 'auto') ga('send', 'pageview') </script>
      <meta name="tsse/config/environment" content="%7B%22modulePrefix%22%3A%22tsse%22%2C%22environment%22%3A%22development%22%2C%22rootURL%22%3A%22/%22%2C%22locationType%22%3A%22auto%22%2C%22EmberENV%22%3A%7B%22FEATURES%22%3A%7B%7D%2C%22EXTEND_PROTOTYPES%22%3A%7B%22Date%22%3Afalse%7D%7D%2C%22APP%22%3A%7B%22name%22%3A%22tsse%22%2C%22version%22%3A%220.0.0%22%7D%2C%22exportApplicationGlobal%22%3Atrue%7D" />
      <!-- EMBER_CLI_FASTBOOT_TITLE --><!-- EMBER_CLI_FASTBOOT_HEAD -->
   </head>
   <body class="body">
      <!-- EMBER_CLI_FASTBOOT_BODY --> <!--JQuERY--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script src="/assets/vendor.js"></script> <script src="/assets/tsse.js"></script>
   </body>
</html>



heroku can't find package.json for Ember fastboot deployment

I've built an Ember (3.4) app which makes use of Ember Fastboot.

It builds and runs OK locally using "ember serve".

Then I deployed it to Heroku. It builds OK but when an attempt is made to access it the Heroku logs contain the following :

2018-10-26T10:59:25.887108+00:00 app[web.1]: Error: Couldn't find /app/dist/package.json. You may need to update your version of ember-cli-fastboot.
2018-10-26T10:59:25.887110+00:00 app[web.1]: at EmberApp.readPackageJSON (/app/node_modules/fastboot/src/ember-app.js:350:13)
2018-10-26T10:59:25.887112+00:00 app[web.1]: at new EmberApp (/app/node_modules/fastboot/src/ember-app.js:34:23)
2018-10-26T10:59:25.887114+00:00 app[web.1]: at FastBoot._buildEmberApp (/app/node_modules/fastboot/src/index.js:114:17)
2018-10-26T10:59:25.887115+00:00 app[web.1]: at new FastBoot (/app/node_modules/fastboot/src/index.js:52:10)
2018-10-26T10:59:25.887117+00:00 app[web.1]: at Worker.buildMiddleware (/app/node_modules/fastboot-app-server/src/worker.js:74:21)
2018-10-26T10:59:25.887118+00:00 app[web.1]: at Worker.start (/app/node_modules/fastboot-app-server/src/worker.js:48:30)
2018-10-26T10:59:25.887120+00:00 app[web.1]: at new FastBootAppServer (/app/node_modules/fastboot-app-server/src/fastboot-app-server.js:53:19)
2018-10-26T10:59:25.887122+00:00 app[web.1]: at Object.<anonymous> (/app/serve.js:3:14)
2018-10-26T10:59:25.887124+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:688:30)
2018-10-26T10:59:25.887125+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
2018-10-26T10:59:25.897530+00:00 app[web.1]: [2018-10-26T10:59:25.897Z][m4] forked worker 4029
2018-10-26T10:59:25.897719+00:00 app[web.1]: [2018-10-26T10:59:25.897Z][m4] worker online
2018-10-26T10:59:25.898240+00:00 app[web.1]: [2018-10-26T10:59:25.898Z][m4] worker exited with error code: 1
2018-10-26T10:59:25.922787+00:00 app[web.1]: Error waiting for process to terminate: No child processes

So the first thing I notice here is that it's looking for package.json in (which I think is) a surprising place. If I browse the files which make up the app on Heroku they look like this :

$ heroku run bash Running bash on ? aaaaa-bbbbbb-99999... up, run.8888 (Free) ~ $ ls -l total 628 -rw------- 1 u12345 dyno 19 Oct 26 10:01 Procfile -rw------- 1 u12345 dyno 1453 Oct 26 10:01 README.md drwx------ 9 u12345 dyno 4096 Oct 26 10:01 app drwx------ 2 u12345 dyno 4096 Oct 26 10:01 config -rw------- 1 u12345 dyno 1004 Oct 26 10:01 ember-cli-build.js drwx------ 116 u12345 dyno 4096 Oct 26 10:02 node_modules -rw------- 1 u12345 dyno 591407 Oct 26 10:02 package-lock.json -rw------- 1 u12345 dyno 1815 Oct 26 10:01 package.json drwx------ 2 u12345 dyno 4096 Oct 26 10:01 public -rw------- 1 u12345 dyno 464 Oct 26 10:01 serve.js -rw------- 1 u12345 dyno 581 Oct 26 10:01 testem.js drwx------ 5 u12345 dyno 4096 Oct 26 10:01 tests drwx------ 2 u12345 dyno 4096 Oct 26 10:01 vendor

The log shows that heroku thinks package.json is going to be inside the dist directory but in fact it's in the root.

I guess i've done something wrong in preparing the app to be deployed to Heroku - can anyone tell me why I'm seeing this error ?


Here are the contents of a few files which may be relevant

Procfile

web: node serve.js

ember-cli-build.js

'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    'asset-cache': {
      include: [
        'assets/**/*',
        'ember-welcome-page/images/*'
      ]
    },
    'esw-cache-fallback': {
      patterns: [ '/' ],
      version: '1' // Changing the version will bust the cache
    }
  });
  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};

serve.js

const FastBootAppServer = require('fastboot-app-server');

let server = new FastBootAppServer({
  distPath: 'dist',
  gzip: true, // Optional - Enables gzip compression.
  beforeMiddleware(app) {
    app.use((request, response, next) => {
      if (request.headers['x-forwarded-proto'] === 'https') {
        return next();
      } else {
        return response.redirect(301, `https://${request.hostname}${request.url}`);
      }
    });
  }
});

package.json

{
  "name": "my-pwa",
  "version": "0.0.0",
  "private": true,
  "description": "Small description for my-pwa goes here",
  "repository": "",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "lint:hbs": "ember-template-lint .",
    "lint:js": "eslint .",
    "start": "ember serve",
    "test": "ember test"
  },
  "devDependencies": {
    "@ember/jquery": "^0.5.2",
    "@ember/optional-features": "^0.6.3",
    "broccoli-asset-rev": "^2.7.0",
    "ember-ajax": "^3.1.0",
    "ember-cli": "~3.4.3",
    "ember-cli-app-version": "^3.2.0",
    "ember-cli-babel": "^6.16.0",
    "ember-cli-dependency-checker": "^3.0.0",
    "ember-cli-eslint": "^4.2.3",
    "ember-cli-fastboot": "^2.0.0",
    "ember-cli-htmlbars": "^3.0.0",
    "ember-cli-htmlbars-inline-precompile": "^1.0.3",
    "ember-cli-inject-live-reload": "^1.8.2",
    "ember-cli-qunit": "^4.3.2",
    "ember-cli-sass": "^8.0.1",
    "ember-cli-sri": "^2.1.1",
    "ember-cli-template-lint": "^1.0.0-beta.1",
    "ember-cli-uglify": "^2.1.0",
    "ember-data": "~3.4.0",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.1.0",
    "ember-maybe-import-regenerator": "^0.1.6",
    "ember-paper": "^1.0.0-beta.18",
    "ember-resolver": "^5.0.1",
    "ember-service-worker": "^0.7.0",
    "ember-service-worker-asset-cache": "^0.6.3",
    "ember-service-worker-cache-fallback": "^0.6.1",
    "ember-source": "~3.4.0",
    "ember-web-app": "^2.3.0",
    "ember-welcome-page": "^3.2.0",
    "eslint-plugin-ember": "^5.2.0",
    "loader.js": "^4.7.0",
    "qunit-dom": "^0.7.1",
    "sass": "^1.14.3"
  },
  "engines": {
    "node": "6.* || 8.* || >= 10.*"
  },
  "dependencies": {
    "fastboot-app-server": "^1.1.2-beta.1"
  }
}




Mocking an ember in-repo-addon service

I have an in-repo-addon:

/my-app/lib/my-service/app/services/my-service.js

import AjaxService from 'ember-ajax/services/ajax';
import ENV from '../config/environment';

export default AjaxService.extend({
    host: ENV.APP.BACKEND_URL,
    contentType: 'application/json; charset=utf-8',

    subscribe(emailAddress) {
       ...
       return this.request(url, {method: 'POST', data: data});
    }

I have a main app component that uses this in-repo-addon.

/my-app/app/components/my-comp.js

import Ember from "ember";

export default Ember.Component.extend({
   myService: Ember.inject.service(),
   ...
});

And that works when the application is run normally. I also have a test for that component.

/my-app/tests/integration/components/my-comp-test.js

import { moduleForComponent, test } from 'ember-qunit';
import ENV from 'my-app/config/environment';

moduleForComponent('sign-up', 'Integration | Component | my comp', {
    integration: true,
});

test('email addresses are trimmed before submission to remote service', function (assert) {
  const signupEmail = " NotAnEmail@example.com ";

  let myService = Ember.Service.extend({

    subscribeUrl() {
      return "";
    },

    request(url, payload) {
      assert.equal("NotAnEmail@example.com", payload.data.emailAddress);
      return new Ember.RSVP.Promise((res) => {
        res({message: 'success'});
      });
    }
  });
console.log("myService=", myService);
this.register('service:my-service', myService);
...

The test tries to create myService and extend it to override/mock various bits to test an assert to make sure the email address has been trimmed.

But myService is always null. It looks like Ember.Service is not including the in-repo-addons when it builds the test, so myService is never found.

I have tried to import the service directly with the following but ember doesn't seem to like that either:

import myService from 'my-app/lib/my-service/app/services/my-service/my-service';
// or
import myService from 'my-app/lib/my-service/app/services/my-service';

Is this a bug with Ember test? How can I fix this?




Ember findRecord will not update dirtyrecords in the store | Ember Data 3.5.0

Im using emberData 3.5.0 where i have change the record from the store and when my view is in edit mode. then when i press cancel, im trying to fetch the record from backend and update in the store. so in my cancel action im calling

      this.store.findRecord( 'profile', id, {reload:true}).then( response => {
        this.controllerFor( 'people/profile' ).set( 'user',response);
        this.controllerFor( 'people/edit' ).set( 'person',response );
})

but the issue is the dirty record which i was changed in edit mode will not be refreshed with this call. ( server call is going for the record).

i tried all the references in ember and forums but i couldn't find a solution for this.




jeudi 25 octobre 2018

Ember JS make a GET request to an API

I want to make a GET request to an api and the request in the server side looks like below, using AJAX

http://localhost:8000/api/?email=test@test.com

In other words, instead, instead of populating data to our ember model using the command, return this.store.query('testmodel',{ email: test@test.com }), I need replace this by a AJAX call in the ember controller

Please Help thanks in advance




customizing adapters for ember api actions

I am referring ember api actions: https://github.com/mike-north/ember-api-actions

Wanted to ask, does someone know if i have an adapter for the model itself but I want to customize the adapter only for one of the member action defined, is it possible to do so?

For example, if my model looks like this:

export default DS.Model.extend({
  userName: attr('string');
  withdrawMoney: memberAction({path: 'actions/withdraw', type: 'POST'})
})

Now adapter for my user model has some headers set. But what I want to do now is if I invoke my member action, then I want to add additional headers. Is it possible to do so without impacting headers globally?




Access sessionStorage in template EmberJS

I have saved some data in sessionStorage (a large JSON response from ajax) in EmberJS, and wanted to know if there was a way to access that directly in template handlebars. If not, what would be my alternatives? I have tried in template but it gives me an error saying "Expecting 'ID', got 'INVALID'".




How to link ember js and spring boot having spring security app

I have an ember app for frontend. I have spring boot app using spring security for providing API's. Through postman I am able to login and use the API's. When I remove the security part from Spring boot app I am able to access all the API's from ember app. Can someone guide me how to link the login part from spring security with ember js? In spring boot I have configured security part such that it validates users using email id and password taking from database mysql.




mercredi 24 octobre 2018

How to store filtered data from JSON and display in table (EmberJS)

I am trying to display a table of records on page load in EmberJS. The data comes from an ajax call, which gives a very large JSON response. Here is an overview of the process (how it should work): Page Loads -> Ajax call ( in controller) -> Response -> Store Data somewhere (filtered) -> Display in Table

So far I have been successful in getting a JSON response, but the data is huge and contains multiple fields and nested fields. I only need to store certain data from the response such as name, email etc.

Here is the code for my controller which is run when the page loads:

import Controller from '@ember/controller';
import Ember from 'ember';

export default Controller.extend({
ajax: Ember.inject.service(),
init:function(){
  const token = sessionStorage.getItem('token')
  this.get('ajax').request('http://127.0.0.1/SugarPro-Full-8.0.0/rest/v10/Leads',{
    method: 'POST',
    headers:{
    'Content-Type': 'application/json',
    'oauth-token': `${token}`
    },
    success: function(response){
      console.log(response);
      sessionStorage.setItem("data", response);
    },
    error: function(){
      window.alert("Please Login!");
      window.location.assign("/login-page");

    },
    dataType: 'json'
  });
}
});

NOTE: I'm storing the response in sessionStorage because I do not know where to go from here, so that may be ignored if required.

PS: I did see a few examples that suggested to put everything in the router, but that was when they assumed the response was a subset of the model, whereas in my case it's probably the other way around.

Many Thanks in advance!




Layout issue in iPad and iPhone safari browser

I am having issue with only iPad and iPhone safari browser. I have attached difference that will show difference between both screen.

In iPad and iPhone safari browser, top of the main container is hidden in the navbar. It's working fine in iPad chrome browser including desktop and android device browser.

enter image description here

We are using bootstrap v3. Here navbar and container-fluid are having position:fixed;

Following are .main-container properties,

position: fixed;
bottom: 0;
overflow-x: hidden;
width: 100vw;

Not sure how to fix this issue just for iPad and iPhone safari? Any help is appreciate.




mardi 23 octobre 2018

ember-cp-validations form error message not showing

I am trying to validate input in a form using ember-cp-validations. The actual validation itself seems to be working, however I cannot get the error message to show on the template. I am fairly new to ember in general, and I am assuming that I am not correctly using the model in the v-get helper.

Here is my model:

const Validations = buildValidations({
    name: validator('presence', true),
})

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

Here is the action I am running in my controller when the form is submitted:

//tried to get character model here to make validation work
let character = this.get('model');

//create new character record to store
let newCharacter = this.store.createRecord('character', {
    name: name,
});

//validating here
newCharacter.validate()
    .then( ({validations}) => {
        console.log(validations)
        if(validations.get('isValid')) {
            console.log('form is valid')
            //record will be saved here
        }else{
            console.log('form is invalid')
        }
    })

In this action when the name field is empty it does say that the form in invalid as expected.

Lastly, I attempt to show the error here:


  
    <div class="error">
      
    </div>
  

The div is created here when you lose focus on the field, but the message never shows. From what I understand, the arguments for the helper here should be the model, the field you are validating, and then the message that is to be displayed. The fact that it knows the form is invalid, but the message never shows leads me to believe that I am misunderstanding something and not actually accessing the character model correctly in the v-get helper.

After reading around, and watching some tutorials on ember-cp-validations I still seem to be stuck. Any help would be appreciated.

Thanks in advance!




how to dynamically update series data using ember-highcharts

I am exploring ember highcharts and i see there is an observer there: "contentDidChange" which they say can be used to change series data and show dynamic updates on the chart. I used the same, and i was able to update the series data but when I invoke chart.redraw() function then my chart does not re-draw itself. Is there anything I am missing?




What does the slash at the end of the parameter in javascript mean?

Below code has '/' at the end of the parameters. What does it mean?

Code extracted from https://guides.emberjs.com/v2.14.0/tutorial/autocomplete-component/

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




How to get current model or model value in ember unit test cases

I'm trying to get model value in ember unit test cases, but its's throwing error like currentModel is destroyed or not define.

Unit test code:

test('test userInfo', function (assert) {
    let appRoute = this.subject();
    let response = {
        "name ": "Test User"  
    }
    appRoute.getUserInfo(response);
    assert.equal(appRoute.get('currentModel.userInfo'), response.name, "userInfo value");
    assert.ok(appRoute);
});

Application route code:

getUserInfo: function (response) {
    this.set('currentModel.userInfo', response.name);
},




Ember - Optional Dynamic Segments in Route

I have a use case and I’m not sure if there is an easy solution within the current Ember router or not, is there a way to define an optional routing param?

I would like to have a dynamic route that might have 1 or might have 2 segments, and then further routes nested inside. My idea of the structure would be something like the below (except the :topic part would be optional)

this.route('course', { path: '/:course' }, function() {
  this.route('page', { path: '/:topic/:page' }, function() {
    this.route('menu', function() {

    });
  });
});

/my-course/my-topic/my-page would hit the page route

/my-course/my-page would hit the page route

/my-course/my-page/menu would hit the menu route

/my-course/my-topic/my-page/menu would hit the menu route




How to use a click function correctly for a specific purpose

  actions: {

I am creating a small game for personal development, its a simple game of connect four and i have created my stage and set the rows and columns to 'undefined' all of this code is fully functional however in the next block-quote you should begin to understand my problem.

    start: function() {
      this.set('playing', true);
      this.set('winner', undefined);
    this.set('draw', false);
    this.set('state', [
      [undefined, undefined, undefined, undefined, undefined, undefined],
      [undefined, undefined, undefined, undefined, undefined, undefined],
      [undefined, undefined, undefined, undefined, undefined, undefined],
      [undefined, undefined, undefined, undefined, undefined, undefined],
      [undefined, undefined, undefined, undefined, undefined, undefined],
      [undefined, undefined, undefined, undefined, undefined, undefined],
      [undefined, undefined, undefined, undefined, undefined, undefined],
    ]);
    this.set('moves', {'x': 0, 'o': 0});
    this.set('player', 'x');
    var markers = this.get('markers');
    for(var idx = 0; idx < 24; idx++) {
      markers.x[idx].visible = false;
      markers.o[idx].visible = false;
    }
    this.get('stage').update();
  }
}

Below is my click function which allows me to click on my grid. The markers created are placed into the clicked grid however i need the markers to drop down the column clicked on to the lowest possible row which is undefined, if it however is already !undefined then it should be in the row just above in the same column. I have added my click function below.

click: function(ev) {
    if(this.get('playing') && !this.get('winner')) {
        if(ev.target.tagName.toLowerCase() == 'canvas' && ev.offsetX < 
           360 && ev.offsetY < 360) {
            var x = Math.floor((ev.offsetX) / 51.5);
            var y = Math.floor((ev.offsetY) / 60);
            var state = this.get('state');
            if(!state[x][y]) {
              var player = this.get('player')
              state[x][y] = player;

          var move_count = this.get('moves')[player];
          var marker = this.get('markers')[player][move_count];
          marker.visible = true;
          if (player == 'x') {
            marker.x = 20 + x * 51.5;
            marker.y = 20 + y * 60;
          } else {
            marker.x = 20 + x * 51.5;
            marker.y = 20 + y * 60;
          }

          this.check_winner();

          this.get('moves')[player] = move_count + 1;
          if (player == 'x'){
            this.set ('player', 'o');
          } else {
            this.set('player', 'x');
          }
          this.get('stage').update();
        }
      }
    }
 },




lundi 22 octobre 2018

Cannot access session data in Ember (JWT Token Data)

I'm using JWT authentication, using ember-simple-auth for implementing user authentication. I m providing necessary details in my project below.

When Authenticated correctly a jwt token is passing from the backend made of djangorest and it contains only a token.

/app/authenticators/jwt.js

import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';

const { RSVP: { Promise }, $: { ajax }, run } = Ember;
export default Base.extend({

  tokenEndpoint: `http://localhost:8000/auth`,

  restore(data) {
    return new Promise((resolve, reject) => {
      // console.log(data.token); token seems empty
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate(creds) {
    const { identification, password } = creds;
    const data = JSON.stringify({
        email: identification,
        password: password
    });
    const requestOptions = {
      url: this.tokenEndpoint,
      type: 'POST',
      data,
      contentType: 'application/json',
      dataType: 'json'
    };
    return new Promise((resolve, reject) => {
      ajax(requestOptions).then((response) => {
        // console.log(response); verified
        const { jwt } = response;
        // Wrapping aync operation in Ember.run
        run(() => {
          resolve({
            token: jwt
          });
        });
      }, (error) => {
        // Wrapping aync operation in Ember.run
        run(() => {
          reject(error);
        });
      });
    });
  },

   invalidate(data) {
     return Promise.resolve(data);
   }
});

/app/authorizer/custom.js

import Base from 'ember-simple-auth/authorizers/base';
// import Ember from 'ember';
import { inject } from '@ember/service';

export default Base.extend({
  session: inject('session'),
  authorize(data, block) {
    const { token } = data
    if (this.get('session.isAuthenticated') && token) {
      consol.log(token);
      // this._super(...arguments);
      block('Authorization', `JWT ${token}`);
      console.log(Authorization);
    }
  }
});

As I tried to access the token using session.data.authenticated.token it shows the value undefined Please help Urgent Thanks in advance




Ember.js: Reloading img tag without src change

I have an img tag as follows:

<img class="avatar" src=""/>

src is bound to a computed property like this:

src: computed('user.avatarUrl', function() {
    var avatarUrl = this.get('user.avatarUrl');
    if (avatarUrl) {
        return avatarUrl;
    } else {
        return null;
    }
})

The user is allowed to upload a replacement avatar. This is done through an ajax request like this:

uploadImage(file) {
    this.set('src', undefined);
    var self = this;
    $.ajax({
        type: 'POST',
        url: user.getAvatarUploadUrl(),
        data: file,
        contentType: 'application/octet-stream',
        processData: false,
        success() {
            // Do something to tell the view to refresh/the image to be re-downloaded
        },
        error() {

        }
    });
}

The catch is that the avatar URL is deterministic based on the account of the user: http://host/users/{user_id}/photo. Therefore after the update, there's nothing to change in the Ember handlebars template and the photo will not change. Even on changing views and back, it does not seem that Ember wants to fully refresh the view.

I think my issue is the same as the dead thread: How do I rerender this img element?

I have tried using notifyPropertyChange in a few different ways, but I don't think the Observer framework will re-render unless the values actually are changed. I don't want something that involves scheduling a delay so a run loop completes with src=null and then a subsequent one completes with src={url} (unless there's seriously no other way to do this).




my ember app which i have not showing server side code on deployment

The Ember app https://thesmilestylist.ca doesn't show server side code view-source: https://thesmilestylist.ca/

This is my package.json:

{
  "name": "tsse",
  "version": "0.0.0",
  "private": true,
  "description": "Small description for tsse goes here",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "lint:js": "eslint ./*.js app config lib server tests",
    "start": "ember serve",
    "test": "ember test",
    "push": "ember build --environment development && git add . && git commit -m \":art:\" && git push "
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^3.0.0",
    "ember-cli": "~3.1.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^6.6.0",
    "ember-cli-dependency-checker": "^2.0.0",
    "ember-cli-eslint": "^4.2.1",
    "ember-cli-fastboot": "^1.1.4-beta.1",
    "ember-cli-htmlbars": "^2.0.1",
    "ember-cli-htmlbars-inline-precompile": "^1.0.0",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-qunit": "^4.1.1",
    "ember-cli-sass": "^7.1.7",
    "ember-cli-shims": "^1.2.0",
    "ember-cli-sri": "^2.1.0",
    "ember-data": "~3.1.0",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.0.0",
    "ember-maybe-import-regenerator": "^0.1.6",
    "ember-resolver": "^4.0.0",
    "ember-route-alias": "^0.1.7",
    "ember-source": "~3.1.0",
    "ember-welcome-page": "^3.0.0",
    "eslint-plugin-ember": "^5.0.0",
    "loader.js": "^4.2.3",
    "minify-images": "^1.0.6",
    "shelljs": "^0.8.1"
  },
  "engines": {
    "node": "^4.5 || 6.* || >= 7.*"
  },
  "dependencies": {
    "ember-cli-meta-tags": "^4.0.0",
    "fastboot-app-server": "^1.1.2-beta.1",
    "serve": "^10.0.0"
  }
}

The app is woking on the local environment, but when I deploy the app, it is not working.




Ember js belongs to relationship

I have two models employee and empdetails

//employee model
import DS from 'ember-data';
export default DS.Model.extend({
    empId : DS.attr(),
    password : DS.attr(),
    email : DS.attr(),
    empdetails : DS.belongsTo("empdetails") 
});

//empdetails model
import DS from 'ember-data';    
export default DS.Model.extend({
    firstName : DS.attr(),
    lastName : DS.attr(),
    dateOfJoining: DS.attr(),
    employee : DS.belongsTo("employee")
});

I use RESTAdapter to make REST calls.

//serializer
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
});

When I try to make a get request for employee I get the below error

Please check your serializer and make sure it is serializing the relationship payload into a JSON API format. Error: Assertion Failed: Encountered a relationship identifier without a type for the belongsTo relationship

Can someone guide me in rectifying the error




Where exactly to add serialize hook (emberJS)

I have been following the EmberJS tutorial at tutorialspoint.com, and was going through the "routes" section, when I came across this page. It explains how to use dynamic segments in ember. So far I understand the code on how the route.js is updated and how the hbs file is created etc. (that's all pretty straightforward). What I don't understand is the last part where a serialize hook is made. I understand the code, but don't exactly know in which file should I put it? There is no mention of it in the tutorial, and I searched stackoverflow as well but the only answer relevant to this was this where it explains how they work rather than where to add them. Can someone please explain in which file should I add this code? Thanks.




dimanche 21 octobre 2018

Ember-Drag-Sort: Nested lists - drag doesn't work on 1st attempt

so I've ran into a weird issue that I've just now noticed about the library. If I have a drag-sort-list (with only 1 item) within another drag-sort-list, whenever I attempt to drag the item inside of the child list i've noticed the drag-event fires, but none of the css classes actually get applied. It's almost like an early return or something. I've even went through the library's code and ensured that all events are firing, yet for some strange reason If only 1 item is in the child list, the initial drag does not work.

diagram below:


parent - [ TOPICS List ]

    child - [ SUBTOPIC LIST ] <--- since this list has 2 items dragging works like normal on first try
          • test topic 1
          • test topic 2 

    child - [ SUBTOPIC LIST ]
          • test topic 3 <--- this is the item that takes two drag attempts




Ember app Installing npm dependencies in a host app

I am referring to the below blog link and have a very specific question;

https://simplabs.com/blog/2017/02/13/npm-libs-in-ember-cli.html

I am referring to the section "npm dependencies"

Basically this is a host app trying to use a child addon & it's dependencies ("moment" library shown for example). So if the child addon is defining "moment" as a "dependency" (not "devDependencies"), would the host app not just install "moment" & work fine ?

Why are the additional steps shown for the resolver algorithm needed ? So essentially what is the purpose of the following additional code shown on that page;

var momentTree = new Funnel(path.dirname(require.resolve('moment/moment.js')), {
  files: ['moment.js'],
});




samedi 20 octobre 2018

Nested routes in ember engine routes.js?

How to define nested routes in ember routable engine? I can't navigate to beyond 2 trees. Like, For example

All posts
 Post
   Comments
     Comment

I can access

localhost:4200/posts/:postid/

But when I access

localhost:4200/posts/:postid/comments/:commentid

Its not rendering the content for comments template. But it doesn't show any error either.




vendredi 19 octobre 2018

How to create dynamic model in ember data

I am trying to create a dynamic ember data models.I have tried this code in route\user like:

var tableColumns = {
   name: DS.attr('string'),
    surname: DS.attr('string')
};
let store = this.get('store');
Ember.getOwner(store).register('model: user', DS.Model.extend(tableColumns));

after creating a model for this.store.findAll(user). but it's not working and it shows model user is not defined.




Ember: Getting model data in the controller

I am new to ember and I am building a DnD character sheet to learn and practice. Right now I am having a lot of trouble getting access to model data in a controller. After hours and hours of reading related posts it is just not clicking and I think I am misunderstanding what I am passing to the controller.

Basically what I am trying to do is grab data from a model so I can do calculations on them and then display the results of those calculations on the page.

Here is my transforms/router.js:

Router.map(function() {
    this.route('characters', { path: '/'})
    this.route('new', {path: 'new'});
    this.route('view', {path: '/:character_id'});
});

So here I am trying to pull up the view page which has the URL of the character id. Next here is my route for the view page:

export default Route.extend({
    character: function () {
       return this.store.findRecord('character', id)
    }
});

So this is finding the record of the character with the id I pass. My link looks like this and is coming from a component:

    <h5 class="card-title"></h5>

Now I have my controller for the view page, which looks like this:

init(id){
    character = this.get('character')
}

This, however, gets me an error saying:

"Error while processing route: view character is not defined ReferenceError: character is not defined"

I've been trying to figure this out for quite a while now, and its getting pretty frustrating. I currently have a work around where I do the calculations beforehand and just store all the calculated results in the model as well, but while I am learning I would like to understand how this works. Thanks is advance.




ember simple auth isnt sending data as post request

i have an ember project using ember simple auth. Im trying to log in through my api which returns an access key but none of my login details seem to be getting sent.

Here is my authentication service. I have console logged the email etc and they are definitly getting passed through

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

export default Service.extend({

    sessionService:    service('session'),

    authenticate: function(email, password, remember)
    {
        this.get('sessionService').authenticate('authenticator:oauth2', email, password, remember).then(() =>
        {

        }).catch((reason) =>
        {

        });
    },
});

Then in my App/Authenticators/oauth2.js I have:

import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
import ENV from 'client/config/environment';

export default OAuth2PasswordGrant.extend({
    //serverTokenEndpoint: 'http://www.mocky.io/v2/5b559561320000b504827e41'
    serverTokenEndpoint: ENV.APP.apiRoot + '/login_request'
});

The api root is correct, on my api i am returning whatever email they have used for testing and its returning nothing which means nothing is getting sent. I can manually write out the url including the email and passwork and that works perfect but that would get a GET request.




Ember simple auth session Expiring(Invalidating) while Reloading

/adapters/application.js

import DRFAdapter from './drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DRFAdapter.extend(DataAdapterMixin, {
    authorizer: 'authorizer:custom',
    namespace: 'api',

    pathForType(){
        return '';
    },
    urlForCreateRecord(){
        return 'http://localhost:8000/api/';
    }
});

my authenticator file is

/authenticators/jwt.js

import Ember from 'ember';  
import Base from 'ember-simple-auth/authenticators/base';  
import config from '../config/environment';

const { RSVP: { Promise }, $: { ajax }, run } = Ember;
export default Base.extend({  

  tokenEndpoint: `http://localhost:8000/auth`,

  restore(data) {
    return new Promise((resolve, reject) => {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate(creds) {
    const { identification, password } = creds;
    const data = JSON.stringify({
        email: identification,
        password: password
    });
    const requestOptions = {
      url: this.tokenEndpoint,
      type: 'POST',
      data,
      contentType: 'application/json',
      dataType: 'json'
    };
    return new Promise((resolve, reject) => {
      ajax(requestOptions).then((response) => {
        const { jwt } = response;
        // Wrapping aync operation in Ember.run
        run(() => {
          resolve({
            token: jwt
          });
        });
      }, (error) => {
        // Wrapping aync operation in Ember.run
        run(() => {
          reject(error);
        });
      });
    });
  },

  invalidate(data) {
    return Promise.resolve(data);
  }
});

login controller:

/login/controller.js

import Controller from '@ember/controller';
import { inject } from '@ember/service';

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

        authenticate: function(){

            let credentials = this.getProperties('identification','password');
            let authenticator = 'authenticator:jwt';
            this.get('session').authenticate(authenticator, credentials).catch(()=>{
                this.set('errorMessage','Login Failed');
            });
            this.set('userData',credentials.identification);

        }
    }
});


/application/controller.js


import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default Controller.extend({
    session: service('session'),
    actions: {
        invalidateSession: function(){
            this.get('session').invalidate();
        }
    }
});

Environment.js file in the /config/ is

/config /environment.js
......
ENV['ember-simple-auth'] = {
    authorizer: 'authorizer:custom',
    // authenticationRoute: 'login',
    routeAfterAuthentication: '/profiles',
    //authorizationPrefix: 'JWT' - do not uncomment this line
    serverTokenEndpoint: '/auth',
  };
......

As you can see in the /config/environment.js file, after authentication the app will redirect to the route profile. and when I refresh the profiles route, the session invalidates automatically. I think the problem is that I haven't store-session(I'm not sure, and don't know how to do that). So please read the codes and help me to solve the issue




Ember this.store.findRecord will not update the existing model

I have a model which im using in a modal model is profile and its look like this.

model/profile.js

  id: DS.attr('string'),
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  email: DS.attr('string'),
  job: DS.belongsTo('job'),

then im using the model in modal by passing through the parent route ( parent route is calling this.store.findRecord('profile', id );

sending the model to modal is works perfectly but when im trying to cancel from the modal i need to send api call again to fetch model data from api and re assign to the model by discarding all changes. i trying to do that in a function which is in the parent route ( child sending an action to parent to execute cancel) .

Action code in route of the parent

  cancelEdit( person ) {

      var profile = person.get( 'content' );

      console.log(  profile.get('id'));

      profile.set( 'uploadedAvatar', null );
      profile.set( 'file', null );


      var image = profile.get('cachedAvatar') ;
      var id = profile.get('id');

      console.log(person);


      this.store.findRecord( 'profile', id, {reload:true}).then( response => {
        console.log(response.get('job'))

        this.controllerFor( 'people/profile' ).set( 'person', response );


        profile.set( 'avatar', image );

        this.controllerFor( 'people/profile' ).set( 'animate', false );

        this.controllerFor( 'people/edit' ).set('isNewPosition',false);

        this.controllerFor( 'people/edit' ).set('imageCropper',false);
        this.controllerFor( 'people/edit' ).set('showImageCropper',false);
        this.controllerFor( 'people/edit' ).set('tmpImage',null);
        this.controllerFor( 'people/edit' ).set('tmpUploadedImage',null);
        this.controllerFor( 'people/edit' ).set('imageBlob',null);

        this.openModal( 'people/profile' );

      } )

    }

but the issue is it wont reset ( refresh or reassign the fresh data set )which is came through the api. the old changed data will be remain the same.

what did i miss here?




jeudi 18 octobre 2018

ember-mocha: Rendering tests for component never gets called

I'm trying to setup some simple BDD tests for an ember project using ember-mocha. I've been following the sample shown in the documentation however the callback that I pass to it() is never called:

import { render } from '@ember/test-helpers'
import { expect } from 'chai'
import { setupRenderingTest } from 'ember-mocha'
import hbs from 'htmlbars-inline-precompile'
import { describe, it } from 'mocha'

describe('UIButtonComponent', () => {

  // debugger // <-- breakpoint is hit if comment removed

  setupRenderingTest()

  it('renders text label', async () => {

    debugger // <-- breakpoint never hit

    await render(hbs`<UiButton @text=test />`)

    expect(this.element.querySelector('img')).to.exist
  })
})

The callback passed to describe() is called, however my actual test never runs. Running the test produces this error in the web based test runner:

enter image description here

Any help would be greatly appreciated!




Ember.js - ember-data - escaped /

I've a model and I use ember-data and inside the line export..., I've qr_code:DS.attr('string') and there're some slash in the qr code like "///"

And then my template I've this

I used triple {} and seems still escape or cutoff the data up to the first slash.

Any idea how I can show what the data it is and not cutoff the data or escapes it?




How to properly declare attribute name on model? (ember.js)

I have an json api which is returning an attribute name sample-products-buy-x-take-y-count with data type number and I declare it to my model like this:

sampleProductsBuyXTakeYCount: DS.attr('number')

But whenever I inspect my model on Ember inspector the value for the sampleProductsBuyXTakeYCount is undefined while the response from my api has value.

May I know what's wrong with my attribute declaration? Thanks!




mercredi 17 octobre 2018

Can I pass an array of object to filterBy?

My ember version is 1.13 and I would like to ask if the line of code below is applicable to the version of my ember app above?

console.log(this.get('arrayOfObjects').filterBy('zoneName', ['zoneNameOne', 'zoneNameTwo'])); ?




Updating ember-moment element when reloading a route in Ember?

I have an Ember app that uses ember-moment.

The application defines a model for site objects:

import DS from 'ember-data';

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

The index route loads site #1 when activated:

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

export default Route.extend({
  model(params) {
    return this.store.findRecord('site', 1);
  }
});

The template for this route is fairly simple:

: 

All of this works as intended. However, I would like to reload the route every thirty seconds.

Thus, I have expanded the route as follows:

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

export default Route.extend({
  model(params) {
    return this.store.findRecord('site', 1);
  },

  afterModel() {
    this.set('_timer',
      Ember.run.later(this, () => {
        this.refresh();
      }, 30 * 1000)
    );
  },

  deactivate() {
    Ember.run.cancel(this.get('_timer'));
  }
});

The status updates when the data returned by the API changes. However, the relative time displayed in the template does not change. I am assuming Ember sees that lastPoll has not changed and does not update the element containing the relative time, even though the current time has changed (and therefore the relative time as well).

What is the correct approach for ensuring that the relative time is updated when the route is reloaded?




How to point an ember app to Staging environment VS Production environment upon deploying a test link?

I am having a problem when it comes to directing a test link to staging environment VS to production environment.

Current behaviour: When I tried to run this command on my terminal ember deploy staging and it created a test link successfully. However, my component has a line of code that checks which environment the app currently pointed to. Unfortunately, it pointed to production environment

Expected behaviour: What I am trying to achieve is when I run the command ember deploy staging it should point to staging environment not production environment

Question: How to tell ember that create a test linkfor a staging environment?

Please see my code below for ../config/deploy.js

/* jshint node: true */

module.exports = function(deployTarget) {
  var ENV = {
    build: {
      environment: 'production'
    },
  };

  ENV['revision-data'] = {
    type: 'git-commit'
  };

  ENV['s3'] = {
    accessKeyId: process.env.S3_ACCESS_KEY_ID,
    secretAccessKey: process.env.S3_ACCESS_KEY_SECRET,
    bucket: 'sample',
    prefix: deployTarget + '/dist/www',
    region: 'us-east-1',
    filePattern: '**/*.{js,css,png,gif,ico,jpg,xml,txt,svg,swf,eot,ttf,woff,woff2}'
  };

  ENV['redis'] = {
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT,
    password: process.env.REDIS_PASSWORD,
    maxRecentUploads: 30
  };

  ENV['gzip'] = {
    'filePattern': '**/*.{js,css,json,ico,xml,txt,svg,eot,ttf,woff,woff2}'
  };

  ENV['rollbar'] = {
    accessToken: process.env.ROLLBAR_ACCESS_TOKEN,
    accessServerToken: process.env.ROLLBAR_SERVER_ACCESS_TOKEN,
    minifiedPrependUrl: 'https://cdn1-' + deployTarget + '.sample.com/dist/www/',
    rollbarConfig: {
      enabled: true,
      environment: deployTarget,
      captureUncaught: true
    }
  };

  if (deployTarget === 'production') {
    ENV.rollbar.minifiedPrependUrl = 'https://cdn1.sample.com/dist/www/';
  }

  return ENV;
};

this is the code of my component that checks which environment you are currently in once you created a test link /components/my-component/component.js

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

export default Ember.Component.extend({

  isProduction: config.environment === 'production',
  myEnvironment: config.environment;
});

And the myEnvironment returns production environment upon logging on my /component/my-component/template.hbs

This is the code of my .env.deploy.staging

CLIENT_HOST=https://staging.sample.com
ASSETS_PREFIX=https://cdn1-staging.sample.com/dist/www/
S3_ACCESS_KEY_ID=ABCDEF123456
S3_ACCESS_KEY_SECRET=ABCDEF123456

ROLLBAR_ACCESS_TOKEN=ABCDEF123456
ROLLBAR_SERVER_ACCESS_TOKEN=ABCDEF123456

Any response is much appreciated. Hoping someone could help me, thank you!




Trouble Placing Tiled Image onto Leaflet Map

I have this straightforward leaflet map (using a standard global background tile) in an Ember app (using Ember leaflet):

enter image description here


I need to place another tile-layer on top of the map, which will be a tiled image - using deep zoom. Specifically, the leaflet-deepzoom plugin for ember.js.

I have a deepzoom image (with a directory ending in _files) but whenever I place it onto the map, it always goes to the top left corner:

enter image description here


Inside of the plugin, it uses this code to define the bounds:

var southWest = options.map.unproject([0, options.height], options.maxNativeZoom);
var northEast = options.map.unproject([options.width, 0], options.maxNativeZoom);
options.bounds = new L.latLngBounds(southWest, northEast);

I've tried messing with this code extensively, attempting to get it to position the image at a coordinate position that I need it at, rather than the default top left.

What I'm realizing though, is that these bounds may not matter, and even if the bounds were correctly positioned in Perth, Australia where I want them, maybe the image would simply be out of bounds, placed in the top left corner, just not visible.


Any guidance at all on how to offset a tiled image to a different coordinate location would be helpful. I've gone through many of the extending Leaflet tutorials and I'm still just not getting it.




How to use route's params in adapter in Ember.js?

Imagine we have an app that allows a user to collect cards and make decks of their cards.

Also, imagine we have in router:

this.route('cards');
this.route('decks', function() {
    this.route('deck', {path: ':deck_name'});
});

And two API endpoints:

  1. GET /cards — to query all cards controlled by a user
  2. GET /decks/:deck_name/cards — to query all cards in the deck with certain deck_name controlled by a user

We have a model of card and want to make different requests depending on the current route (to the first endpoint for our app's /cards route, and to second for /decks/:deck_name route).

How to write an adapter for card model to query the right endpoint depending on the route?


We use Ember v2.18.




Redirect shorthand URLs with children to normal URL

I'm attempting to implement shorthand URLs which redirect to the regular URLs to make URLs easier and shorter to type in the address bar. I'm attempting to implement this for the crates.io website.

To clarify what I mean, I would like to redirect URLs like this:

  • /c => /crates
  • /c/rand => /crates/rand
  • /c/rand/0.5.5 => /crates/rand/0.5.5
  • /c/rand/... => /crates/rand/...

Here is a snippet of the relevant routes as currently configured:

this.route('crates');
this.route('crate', { path: '/crates/:crate_id' }, function() {
    this.route('download');
    this.route('versions');
    this.route('version', { path: '/:version_num' });
    this.route('reverse-dependencies', { path: 'reverse_dependencies' });
    this.route('owners');
    this.route('docs');
    this.route('repo');
});

I did attempt to implement these redirects by defining the following additional routes:

this.route('c');
this.route('c', { path: '/c/:crate_id' });

With this ./routes/c.js:

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

export default Route.extend({
    afterModel(crate, path) {
        if (crate === undefined) this.transitionTo('crates');
        else this.transitionTo('crate', crate, path);
    },
});

This does only partially work. The /c and /c/rand routes are covered and work, while the others such as /c/rand/0.5.5 don't work.

I can implement all child route possibilities, but I don't feel that's the right way of doing it. I would like to prevent duplicate code.


How would I implement this properly? Is it possible to redirect anything starting with /c to their respective long routes? I've looked into the ember documentation, but didn't find the solution. I feel there must be a better way than what I've tried.




Passing a Handlebars component output as a parameter to a helper

I'd like to use the output of a component as a parameter to my helper, but am not having much success.

My Ember template is something like this:

<td class="wrap">
  
</td>

and the helper:

import { helper } from '@ember/component/helper';
import { htmlSafe } from '@ember/string';

export function helperFunction (params) {
    if (!params) {
        return "";
    }

    var link = params[0];
    if (!link) {
        return  "";
    }

    var linkText = params[1];
    if (!linkText) {
        linkText = link;
    }

    return new htmlSafe('<a href="' + link + '">' + linkText + '</a>');
}

export default helper(helperFunction);

The two combined successfully generates:

<td class="wrap">
  <a href="http://stackoverflow.com">Visit</a>
</td>

Now I have a component (my-component.hbs) that outputs HTML with the following:


  <span class="red"></span>


This component works if it is referenced in the template like so: (renders <span class="red">alphabet</span> as expected).

But I am stumped trying to get the HTML output into the second parameter of generate-url to produce:

<td class="wrap">
  <a href="http://stackoverflow.com"><span class="red">alphabet</span></a>
</td>

I have tried naively , but that outputs errors when that particular Handlebar is evaluated.




Drag and drop file to specific target

I have a set of elements of media files listed like this.

enter image description here

I want to upload a a media file from windows explorer to a specific target of this list(for eg- It should be possible to add file above 'Title A' or below 'Title A'... ). How to achieve this?I know how to upload a file and it is achievable for me if it's to add to the end of the list. What I don't get is how to get that specific position which I need to upload.

(If it's a DOM element, I could have used jQuery draggable droppble, but again it's not possible here! :(. )

Any help?!

Thank you.




Select statement using handlebars in Ember

/ exams / template.hbs

<form>
  <select name="selectvalue" id="selectvalue">
     <option value="one"> One </option>
     <option value="two"> Two </option>
     <option value="three"> Three </option>
  </select>
  <button type="submit" > Submit </button>
</form>

/ exams / controller.hbs

import Controller from '@ember/controller';
export default Controller.extend({
    actions: {
        printans: function(){
            let val = this.get('selectvalue');
            console.log(val);
        }
    }
});

All I need is I want to replace the html code in the template.hbs with handlebars, and when the form is submitted, I need to pass the value to the controller.

Thank you




Ember difference in naming specified in package.json V/s index.js

For an Ember addon/engine project, what is the difference in the name specified in package.json V/S the one specified in index.js

package.json
{
  "name": "parent-my-ui",
  "version": "1.0.0"
}

index.js
module.exports = EngineAddon.extend({
    name: 'my-ui',
});

Is it fine to have different names for both? What is the practical usage of both of them (specifically in a parent/child engine kind of setup) ?




mardi 16 octobre 2018

What is mixin in ember js?

Can anyone explain why mixin is important ?

How or where can we use the mixin to get the best out of mixin?

https://www.emberjs.com/api/ember/release/classes/Mixin

I've referred here but it's not quite elaborate




How to build a table with multiple models

I am new to ember and I am trying to figure how to show different model hooks on a component. I have two models that I want to show in a table. Each model should show when the link-to route is clicked, but I want to use one component to build the table like so

let newCol = [];

export default Component.extend({
table:null,
model:null,
columns:computed(()=>{
    return newCol;
}),
init(){
    this._super(...arguments)
    let model = this.get('model')


        for(const key of Object.keys(model[0])){
            newCol.push({'label': key});
            newCol.push({'valuePath': key});
            //console.log(key)
        }

        let table = new Table(this.get('columns'),this.get('model'));
        //console.log('table = ', table);
        this.set('table',table);
}
});

I am passing all my model hook from my routes like this



and my menu is created like this


<li></li>


this creates a menu like user, files when I click the user menu it display the users data on the table but if when I click the files menu then the table doesn't reset to show just the files data. It shows the user and the files data.




how can i inject a service in adapter emberjs?

I'm trying to inject a service in my adapter but i'm receiving this error: "Assertion Failed: Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container."

Can someone show me how can i inject a service in adapters?




Where do I add and remove event listeners in the Ember controller life cycle?

If I want to listen for certain events or callbacks only on a certain route, and stop listening when not on that route. Where would I write that code?

There are a lot of hooks and events in an Ember component life cycle, but I cannot find any documentation on where to listen and unlisten for route-specific events or callbacks.

An example would be Listening to GPS coordinates:

// Listen
this.set('watch', navigator.geolocation.watchPosition(navigator.geolocation.watchPosition(watchFn))

// Unlisten
navigator.geolocation.clearWatch(this.get('watch'))

(Note that I want to listen on the route/controller, not on a component.)

First thought is to set the watch at __init(), but the controller is a singleton so this will fire only once.

Second thought is to set actions for activate() and deactivate() in the route, but they don't seem to fire so they are not what I think they are.

Then there is setupController() and resetController(). The resetController() seems to work reliably indeed and fires every time I leave the route. But setupController() also seems to fire only once. Which might make sense, since the controller is a singleton.

Then I thought I could use willTransition() or didTransition() in stead of setupController(). They work as expected for starting the listeners when navigating to a different route first.

But when I navigate away to a route that redirects back to this route, although both hooks executed, it seems like resetController() is fired after didTransition(). I'm not sure if that's what happens, but the effect is the same: The listeners stop listening, but they don't start listening. If I navigate away to an unrelated route and back again, the listeners will be activated again.

I'm stuck in the maze of possibilities.

  1. How can I achieve this? (I assume this is a normal approach. But if not: I'm out of time. Willing to do ugly hacks at this point.)
  2. Is there a best practice and/or "Ember way" to achieve this type of on(x) off(x) behavior?