dimanche 30 décembre 2018

Run Ember.run.later from action triggered

I am having problem with action handling in Ember controller. I want to run some function continiously after edit button is clicked in hbs. I have tried it like this in action.

openEditWindow() {
  this.set('someChangingValue', true);
},

Here is the function that reacts to action someChangingValue change.

someChangingValue: false,    

someTestFunction: observer('someChangingValue', function(){
 var test = this.get('someChangingValue');

if(test === true){
  Ember.run.later((function() {
    this.functionThatIsRunningEachTwoSeconds();
  }), 2000);   
} else {
  console.log('this should not do anything');
}
}),

But this runs functionThatIsRunningEachTwoSeconds only once. Also tried the same functionality with changing someChangingValue to false if true and otherwise, that put me in infinite loop of observing property.

Thanks!




Empty output from JSON encoding

In Firefox the http response is shown as '{}', but the alert in the client side code prints '[object object]'. I would have expected something resembling '{logoutGoogle : "true" , logoutUrl : "/_ah/logout?continue=http%3A//localhost%3A8080/"}' in the Firefox tool that show the XHR response.

I verified that the failure is the same with 'tada' as logoutUrl instead of '/_ah/logout?continue=http%3A//localhost%3A8080/'.

Code compiles and runs and I have included comments in the client and server code below to show what the results of me trying to inspect the running code with logs and with alerts are.

Client side code inside an emberjs component:

export default Component.extend({
    userUiLanguageService : service(),
    ajax : service(),
    actions: {
        logoutOnlyWebApp(){
            alert(this.get('ajax').request('/logout',{
                method : 'GET',
                data: {
                    logoutGoogle : false
                }
            }));
        },
        logoutAllOfGoogle(){
            //alert prints [object object]
            //not undefined as I would have expected
            //from the Firefox http response tool
            // that shows '{}' as the server response
            alert(this.get('ajax').request('/logout',{
                method : 'GET',
                data : {
                    logoutGoogle : true
                }
            }));
        }
    }
});

Server side go code:

type LogoutOutput struct {
    logoutSuccessful string
    logoutUrl string
}

func logout(w http.ResponseWriter, r *http.Request){
    c := appengine.NewContext(r)
    u := user.Current(c)

    if u == nil {
        http.Redirect(w, r, "/", http.StatusSeeOther)
        return
    }

    logoutGoogle:=r.URL.Query().Get("logoutGoogle")
    //below prints 'true'
    log.Errorf(c,"%v",logoutGoogle)
    logoutGoogleBool:=false
    if logoutGoogle == "true" {
        logoutGoogleBool=true
    } else if logoutGoogle == "false" {
        logoutGoogleBool=false
    } else {
        log.Errorf(c,"Value is not true or false",logoutGoogle)
    }

    url := ""
    var err error
    if logoutGoogleBool { // LOGOUT ALL OF GOOGLE
        url, err = user.LogoutURL(c, "/")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    }

    //below prints '/_ah/logout?continue=http%3A//localhost%3A8080/'
    log.Errorf(c,"%v",url)
    logout_output:=LogoutOutput{logoutSuccessful:"true",logoutUrl:url}
    logout_output_json,err := json.Marshal(logout_output)
    //below prints '[123 125]'
    log.Errorf(c,"%v",logout_output_json)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    //w.Header().Set("Location", url)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(logout_output_json)
    //fmt.Fprintf(w,logout_output_json)
}




samedi 29 décembre 2018

Why do I get "Ajax authorization fails" in my tests

I am following the ember tutorials, and specifically I'm on services.

I am 99.9% certain that I have the exact code in place -- I am copying by hand, because I believe that helps me absorb it more completely, but if anything fails I start using a diff checker to see if I made a typo. To my knowledge, no typos.

The App I have written performs identically to the screen shots in the tutorials, and the only error I get is a lint error for having a test that doesn't have an assert in it (yet).

Prior to this unit, all other tests have passed as well. But now I am getting failed tests that previously passed. They appear to all stem from the stubbed call to the map service failing. The first test that fails is integration/component/rental-listing-test.js:

hooks.beforeEach(function() {
  this.rental = {
    image: 'fake.png',
    title: 'test-title',
    owner: 'test-owner',
    type: 'test-type',
    city: 'test-city',
    bedrooms: 3
  };
});
test('should display rental details', async function(assert) {
  await render(hbs``);
  assert.equal(this.element.querySelector('.listing h3').textContent.trim(), 'test-title', 'Title: test-title');
  assert.equal(this.element.querySelector('.listing .owner').textContent.trim(), 'Owner: test-owner', 'Owner: test-owner');
});

If I remove the new line from rental-listing.hbs ( ), thus preventing the map from being used, these tests once again pass (though the new tests for the component using the service have issues).

So either I am doing something wrong that I can't find, or else the fine folk at emberjs.com have not provided complete information in this tutorial. Do I need to somehow stub the map service? that appears in the .hbs file for the above test to pass? If so, why do you think they failed to mention this?




Store a global variable from ajax call

I have a list of years in an array format [2018, 2019, 2020] that is returned from my back end. Right now, i’m using a setup controller to make the ajax call and set it as a value to be used by my ember-power-select. However, I just need this to be done once, like on application load and have it as a global variable, instead of everytime the controller loads since this array will rarely change.

How should I go about this ?




vendredi 28 décembre 2018

Why is my feature flag displaying as true?

Today we realized that our feature flag controls 2 features but we only want it to control one. I created a second feature flag called displayNewPage. I wrapped the new page under development in an if so that it will be hidden from users.

The code works locally but when I deployed it to production it doesn't work. On production when the Get request to the current user is done it receives the displayNewPage as false.

When I checked the ember data it doesn't seem to know about the new boolean even though I have added it to the frontend model. The page displays the link to the new page but I don't really understand why this is.

Does anyone have any suggestions?




jeudi 27 décembre 2018

Can't import styles from add-on after migrating to module unification structure in an ember app

I used the ember-module-migrator to migrate an Ember app to the new file structure and followed the instructions here: https://github.com/emberjs/ember.js/issues/16373.. Now when running the tests or the app i get a lot of errors of course :P but the following error is making me crazier than normal:

Error: Can't find stylesheet to import.
@import 'kci-style/addon';

but the addon is present in the node_modules folder.
I suspect that this might be related to that the addon is still using the old file structure...
I made sure that I have setup the fallback resolver correctly (as mentioned here: https://github.com/rwjblue/ember-module-migrator) but it still won't import the styles from the addon...

I even tried migrating the addon in the node_modules to the module unification structure but that also didn't help... any suggestions would be appreciated.

Thanks in advance...




mardi 25 décembre 2018

How can I pass properties of parent component to a child component without explicitly naming them?

Let's assume there is a parent component A, which has a child component B, which in turn has a sub child C.

// Template A 


// Template B


Template C will list all the params sent to it. There is no fixed length or name for the params.

My objective is (from B) is to receive params from A and send all of them into C. How could I obtain the list of params and send them to child with binding intact with A ?




lundi 24 décembre 2018

How is Glimmer VM different from a virtual dom?

So I recently started looking into ember js, especially its glimmer rendering engine and trying to understand how it works.

So my understanding is that Glimmer VM is a virtual machine that emulates the actual DOM and executes functions to make updates to it. While a vdom maintains an internal representation of the DOM states, glimmer VM has no such state, instead, it executes two sets of linear instruction - one to do the initial render of the template and the second set to make updates to the elements. The main benefit of this approach is that this way we can completely bypass the parse/compile bottleneck of JS and just send a binary to the client which is then executed of the glimmer vm. Am I getting this right?




Ember three.js obj

i am using ember framework and testing three.js and i will need to import ojb file into the ember component.

i am am following and using this package https://www.npmjs.com/package/three-obj-mtl-loader

my code

import Component from '@ember/component';
import THREE from 'three';
import {MTLLoader, OBJLoader} from 'three-obj-mtl-loader';

export default Component.extend({
    didInsertElement(){
        var scene = new THREE.Scene();
        var manager = new THREE.LoadingManager();
        var renderer, camera, banana;

        var ww = window.innerWidth,
            wh = window.innerHeight;

        renderer = new THREE.WebGLRenderer({
            canvas: document.getElementById('scene')
        });
        renderer.setSize(ww, wh);

        camera = new THREE.PerspectiveCamera(50, ww / wh, 0.1, 10000);
        camera.position.set(0, 0, 500);
        scene.add(camera);

        manager.onProgress = function (url, itemsLoaded, itemsTotal){
              console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
        }

        manager.onError = function ( url ) {

              console.log( 'There was an error loading ' + url );

        };

        var render = function() {
            requestAnimationFrame(render);

            banana.rotation.z += .01;

            renderer.render(scene, camera);
        };

        var loadOBJ = function() {
            //Loader for Obj from Three.js
            var loader = new OBJLoader(manager);

            //Launch loading of the obj file, addBananaInScene is the callback when it's ready
            loader.setPath('/assets/3d/');
            loader.load('banana.obj', function(object) {
                banana = object;
                //Move the banana in the scene
                banana.rotation.x = Math.PI / 2;
                banana.position.y = -200;
                banana.position.z = 50;
                //Go through all children of the loaded object and search for a Mesh
                object.traverse(function(child) {
                    //This allow us to check if the children is an instance of the Mesh constructor
                    if (child instanceof THREE.Mesh) {
                        child.material.color = new THREE.Color(0X00FF00);
                        //Sometimes there are some vertex normals missing in the .obj files, ThreeJs will compute them
                        child.geometry.computeVertexNormals();
                    }
                });

                scene.add(banana);
                render();
            });
        };

        loadOBJ();
    }
});

the console said is loaded into but i did not see any model at screen , i found out i got a 304 error in feteching the ojb file.

if someone know what wrong with it can you let me know ? thanks appreciate your help.




dimanche 23 décembre 2018

Actions in Route Handler

I've done couple of projects in Ember so I am not completely new to it. In my last project about a year ago I used ember-route-action-helper addon to have all my actions in routes instead of creating a controller. I recently started another project and noticed I can handle actions in routes without using this addon.

I did search on google but didn't get any clue. Is this a new feature added in Ember and is there any drawback to handle actions in routes instead of controller? Besides, what's the use of controller now?

Thanks




How to normalize data in meber.js

I have related data Attribute --> Values in meta section.

pushPayload works fine

this.store.pushPayload(res.products.get('meta.attributes'))

But I need push into model only new data, so I try to normalize:

model.set('attributes', this.store.normalize('attribute', res.products.get('meta.attributes')));

During normalize I got error:

string.js:63 Uncaught TypeError: Cannot read property 'replace' of undefined
    at Cache.func (string.js:63)
    at Cache.get (ember-metal.js:2611)
    at decamelize (string.js:100)
    at Cache.func (string.js:11)
    at Cache.get (ember-metal.js:2611)
    at Object.dasherize (string.js:104)
    at normalizeModelName (-private.js:560)
    at Class.modelNameFromPayloadKey (json-api.js:352)
    at Class._extractType (json-api.js:338)
    at Class.normalize (json-api.js:379)

So what is the error here? I don't want write loop on meta.attributes and use peekRecord




samedi 22 décembre 2018

DataTables in Ember Project

I am not completely new to Ember and DataTables and have used both of them together in earlier projects. However, in my new project I am facing a problem. Whenever I try to include DataTables javascript (jquery.dataTables.js') file, I get following error on browser console:

jquery.js:286 Uncaught TypeError: Cannot set property [] of [object Array] which has only a getter
    at Function.jQuery.extend.jQuery.fn.extend (jquery.js:286)
    at jquery.dataTables.js:14633
    at jquery.dataTables.js:56
    at jquery.dataTables.js:59
jQuery.extend.jQuery.fn.extend @ jquery.js:286
(anonymous) @ jquery.dataTables.js:14633
(anonymous) @ jquery.dataTables.js:56
(anonymous) @ jquery.dataTables.js:59
loader.js:247 Uncaught Error: Could not find module `ember-resolver` imported from `peptalk-web/resolver`
    at missingModule (loader.js:247)
    at findModule (loader.js:258)
    at Module.findDeps (loader.js:168)
    at findModule (loader.js:262)
    at Module.findDeps (loader.js:168)
    at findModule (loader.js:262)
    at requireModule (loader.js:24)
    at app-boot.js:3
missingModule @ loader.js:247
findModule @ loader.js:258
Module.findDeps @ loader.js:168
findModule @ loader.js:262
Module.findDeps @ loader.js:168
findModule @ loader.js:262
requireModule @ loader.js:24
(anonymous) @ app-boot.js:3

My ember-cli-build.js file looks like following:

  app.import('vendor/bootstrap/dist/css/bootstrap.min.css');
  app.import('vendor/font-awesome/css/font-awesome.min.css');
  app.import('vendor/Ionicons/css/ionicons.min.css');
  app.import('vendor/datatables.net-bs/css/dataTables.bootstrap.css');
  app.import('vendor/adminlte/dist/css/AdminLTE.min.css');
  app.import('vendor/adminlte/dist/css/skins/skin-blue.min.css');

  app.import('vendor/bootstrap/dist/js/bootstrap.min.js');
  app.import('vendor/datatables.net/js/jquery.dataTables.js');
//  app.import('vendor/datatables.net-bs/js/dataTables.bootstrap.js');
  app.import('vendor/adminlte/dist/js/adminlte.js');

  return app.toTree();




vendredi 21 décembre 2018

Force tab to specific element

I am inside of a tab panel. Once a tab is selected I can tab through three columns of list items. At the end of each column is a button. Once the tab reaches the last column, last element in the column the tabpanel is closed and moves to the next element on the page.

My expectation is that once it reaches the last column, last element that it would move to the next Tab and so forth until it reaches the last element in the last tab.

My idea was to add an event listener to the last element, that listens for a ‘keyup or a focus out’ event that will apply focus or a tabindex to the next desired element

const lastElementBtn = $('.panel-column__last-element’);

lastElementlBtn.addEventListener('keyup', event => {
  if (event.code == 'Tab') {
    getFocus();
  }

  function getFocus() {
    $(‘.panel-tab__next’)
      .parent()
      .focus();
  }
});

The next tab is still not receiving focus




How to use flexbox with ember?

I am struggling to use flexbox with ember. I installed the addon ember-flexboxgrid-sass

It says to add @import flexboxgrid; to the app.scss file. But I didn't have an app.scss file. So I created one.

Then I thought maybe I needed a sass addon so I installed ember-cli-sass.

That didn't work either. I feel like it should be straight forward but I can't get it working.

Does anyone have any suggestions?




jeudi 20 décembre 2018

How to output multiple css files in Ember app

I am doing an ember build and I have 3 stylesheets that need to compiled into their own stylesheets.

This is how the ember-cli-build.js is by default

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

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    'ember-cli-foundation-6-sass': {
      'foundationJs': 'all',
    },
  });

And this is what I have tried but I don't see new files generated. The file paths are correct.

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

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    'ember-cli-foundation-6-sass': {
      'foundationJs': 'all',
    },
    css: {
      '/components/icons.data.svg': '/assets/icons.data.svg.css',
      '/components/icons.data.png': '/assets/icons.data.png.css',
      '/components/icons.fallback': '/assets/icons.fallback.css',
    },
  });




Google one-tap log in with Auth0

We currently user AuthO as a platform to allow for google login and sign up on our site, but I want to start using the google one tap login https://developers.google.com/identity/one-tap/web/overview

Is there a way for us to be able to set up the one tap log in while continuing to use Auth0 as a platform?

The idea is to not have an external connection into google's identity and login/sign up features outside of our standard infrastructure.




mardi 18 décembre 2018

In EmberJs, how to multi-select the list of filenames and identify the selected filenames with save or submit button

I have template which shows list of 'filenames and its description', something like below:

(Name) ------ (Last Modified) -----(Created By)

tower.jpg ------ 02/08/2015 ---------- Tom

icon.pdf ------ 04/02/2018 ------------ Harry

....

Like above, I have many rows for the 'filename and its description'. Can anybody know how to multi-select these files and identify the multi-selected file names using save or submit button? Also, I have tried with tags but since it is a drop down, couldn't achieve for single row multiple values. Any references, links or ideas would be helpful.

Also, my version of ember is 2.11.




Ember data: computed attributes

I like to know if there is way to use computed properties with ember data for example I would like to have totalPrice calculated and saved from based on amount of other properties. Only way I think I can think of doing it using an observer




Using multiple yields in Ember to display header, body, footer in different places

How to use multiple yields in Ember to display header, body, footer in different places? Added below a sample code for reference. But not working and throws the error saying,

Assertion Failed: A helper named "ib.footer" could not be found

components/common/info-bar-footer.hbs:



components/common/info-bar-header.hbs:



components/common/info-bar.hbs:

<div class="info-bar" style="display: ">
    <div class="info-bar-header">
        <button class="btn-close" data-dismiss="info-bar" >x</button>
        
    </div>
    <div class="info-bar-footer">
        
    </div>
</div>

templates/home.hbs:


    
        <p class="info-content">
            Hello, nice to see you again
        </p>
    
    
        <button class="btn-default">Ok</button>
    





Adding a class dynamically to hide only yield part of the ember component without wrapping

Is there any way to add a class(In my case it is hide class) dynamically to hide(display : none) only yield part of the ember component without wrapping the yield part of the component with tags (div,span or anyother) in Ember JS?

My Case :

 
     <p>Loading....!</p>
 
 <div class="">
     
 </div>

Here I want to hide the yield part without wrapping it up by a div tag

Note : I can't use If Else statement as it will create a new instance of component every time isLoading property changes. This is a component to show loading




lundi 17 décembre 2018

How to interact with ember jsonapi query which contain multiple models

Suppose I make query in my route

 RSVP.hash({
   topics: this.get('store').query('topic', {'filter': data})
 })

And back-end response jsonapi which contain two model together:

 "data": [{
    "type": "topic",
    "id": "1",
    "attributes": {
      "title": "JSON:API!"
    }
   "type": "filter",
    "id": "1",
    "attributes": {
      "title": "JSON:API!"
    }
]

NOTE: filter don't have any relations with topic and Data goes to ember store in a right way.

REASON: filter - is a some metadata which already exist in back-end during quering topic and quite ’costly’ make additional query like this.get('store').query('filter', {'filter': data}).

QUESTION How I can recognize type in result Ember, or how to deal with multiple types (without relations) in one response in general.

RSVP.hash({
  topics: this.get('store').query('topic', {'filter': data})
}).then((res) => {
   res.topics.forEach((i) => {
    //detect which i type here
   })
});




Ember.js test page keeps refreshing automatically

I'm trying to follow an example integration test from here: https://guides.emberjs.com/release/testing/testing-components/ (Testing Actions)

My problem is that the Test output keeps refreshing automatically, perpetually, for some reason?

Test code:

test('Can handle submit action', async function (assert) {
    /*
    * THIS TEST HAS PROBLEMS
    * THE PAGE CONSTANTLY REFRESHES FOR THIS TEST, NO IDEA WHY, NEED TO INVESTIGATE
    */
    assert.expect(1);

    // test double for the external action
    this.set('externalAction', (actual) => {
      const expected = {inputValue: 'test'};
      assert.deepEqual(actual, expected, 'submitted value is passed to external action');
    });

    await render(hbs``);

    // click the button to submit the form
    await click('#submitButton');
  });

Component.js:

import Component from '@ember/component';
import {computed} from '@ember/object';

export default Component.extend({
  inputValue: '',
  submitText: 'Save',
  inputIsValid: computed('inputValue', function () {
    return this.inputValue.length > 3;
  }),

  actions: {
    save(inputValue) {
      if (this.inputIsValid) {
        this.saveAction(inputValue); // pass action handling to route that uses component
      }
    }
  }
});

component template:

<br>
<br>
<form onsubmit=>
    
      <div style="color: red" class='validationMessage'>
        Hey it is not valid!
      </div>
    

    <label id="inputLabel"></label>
    
    <br>
    <button type="submit" id="submitButton" class="btn btn-primary"></button>
</form>


I thought it might be because the form in the template keeps submitting, but that can't be the case since it should only click submit once. Any help much appreciated!




dimanche 16 décembre 2018

Is there an AWS API for getting list of all regions?

currently I am developing a form as below with Ember:

Ember form

My question is: Is there an API which helps me to fill in this select form ? Because I don't want to manually type in the code and then have to change it again if AWS add more regions in the future. Thanks in advance.




vendredi 14 décembre 2018

Implementing computer player

This is the click function. I've inserted a computer player and need it to replicate what the users click does. It is a connect four game.

 click: function(ev) {
  var component = this;
  if(component.get('playing') && !component.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));
        var state = component.get('state');
        var gridHeight = state[0].length;

        for(y = 1; y < gridHeight; y++ ) {
          if(state[x][y]) {
          //this cell is occupied, so choose the cell above y
          break;
        }
    }

      y = y - 1;

This is what makes the users counter go up one when the desired spot is already occupied

        if (!state[x][y]) {
          var move_count = component.get('moves')['x'];
          var marker = component.get('markers')['x'][move_count];
          state[x][y] = 'x';
          marker.visible = true;

          marker.x = 25 + x * 51.5;
          marker.y = 20 + y * 60;
          component.check_winner();
          component.get('moves')['x'] = move_count + 1;
          setTimeout(function() {
            if(!component.get('winner')&& !component.get('draw')) {
              var move = computer_move(state);
              move_count = component.get('moves')['o'];
              state[move.x][move.y] = 'o';
              marker = component.get('markers')['o'][move_count];
              marker.visible = true;
              marker.x = 25 + move.x * 51.5;
              marker.y = 20 + move.y * 60 ;
              component.get('moves')['o']= move_count + 1;
              component.get ('stage').update();
              component.check_winner();
            }
          }, 200);
        }
     console.log(state);
  }

} },

I need the computer to be able to drop the counters in the same fashion as the user




Ember - Mirage fails when models are in sub-folders

I have little experience in Ember. Im not in control of the server and so path to certain resources are different as JSONAPI specs but for the most part it matches it.

I have the following structure for my models:

/models
|-- myModel
|-- generalModel (polymorphic model)
|--/generalModel 
     |--modelTypeA
     |--modelTypeB

where myModel hasMany generalModel being declared as polymorphic. Taking into account that it is a polymorphic model, when I use the method findRecord('my-model', id, {include: 'general-models'}) the responses tend to be like:

response: {
  data: {
    attributes: {...},
    id: XXX,
    relationships: {
      general-models: {
        data: [
          { type: 'general-model/model-type-a', id: YYY }
        ]
      }
    }
  }
}

How can I modify the responses in mirage, so instead of { type: 'general-model/model-type-a', id: YYY } I would return { type: 'general-model-a', id: YYY }?

This is a simplify scenario, so the focus is in what hook mirage provides to modify the type in relationship when using subfolders for models.

I have tried using serializers for general-model but it seems that they dont get call at all. Mirage does not support subfolder structure in models, so I cannot defined a serializers for model-type-a. It crashes saying Assertion Failed: Subdirectories under BLABLA are not supported.

I have seen https://github.com/samselikoff/ember-cli-mirage/issues/663 and https://github.com/samselikoff/ember-cli-mirage/issues/540 and I dont know workaround.

Any ideas?




Changing request headers on http 302 redirect in Ember

I have a situation where I am sending out a request to our api endpoint passing an authorization: bearer token in the request header. The response comes back as HTTP 302 and the browser sends out a new request to an AWS S3 bucket, which then fails with a 400 as it also has an X-Amz-Algorithm parameter in addition to the authorization header.

How would I go about removing the authorization header once the initial request responds with a 302 error?

This is using Ember 3.5.1

Thanks




Ember js: How to increment a property in a controller while it is consumed in the template?

How to increment a property in a controller while it is consumed in the template?

Case : I will pass a property to a component multiple times and I want to calculate how many times I've used that component in my application




jeudi 13 décembre 2018

Cordova - Displaying local image files in a tag

I have a Cordova app (built on Ember.js, using the Corber addon) that I am currently only running on iOS, specifically the iOS simulator (iPhone 8, iOS v12), so it is using a WKWEBVIEW.

The app is using cordova's file plugins to download remote images and store them on the user's device, currently in the "Documents" (cordova.file.documentsDirectory), which works fine, and I've verified that the images do in fact exist there. However I can't figure out the correct URL/URI to use to display those images in the app via standard <img> tags.

Cordova's own documentation says to use the cdvfile:// protocol path (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/#cdvfile-protocol), but even with following the instructions there (adding the content-security meta tag to the index.html, the access rule to the config.xml, etc), it seems like WKWEBVIEW just flat out does not support this protocol, giving me "unsupported URL" errors in the console when I attempt to use it.

Other SO answers on the subject suggest using a normal URL path relative to the cordova app's web server URL, e.g. things like <img src="/Library/NoCloud/path-to-my/file.jpg"> but any path I try 404's.

This seems like such a simple/common use case, but I'm stumped.




mercredi 12 décembre 2018

Specify parent in API request

I'm pretty new to ember and have been somewhat thrown in at the deep end with it so there's a good chance I'm missing something that should be incredibly obvious here.

Anyway, my rails application has defined a route as /api/1/publications/:publication_id/catalogs. This is working fine.

However, I cannot for the life of me get Ember to use this route, everything I try either results in a request to /api/1/catalogs - or no request at all.

My router.js file has:

Router.map(function() {
  this.route('publication', { path: '/publication/:publication_id' }, function() {
    this.route('catalogs', { path: '/publication/:publication_id/catalogs' });
  });
});

My publications model has

catalogs: DS.hasMany('catalog'),

My catalog model has

publication: DS.belongsTo('publication')

And, amongst a few others lost to undo's, I have tried the following methods of querying this data in my route .js file

model() {
  this.modelFor('publication.name')
  var output = {
    model: this.modelFor("publication")
  };

  let publication = this.modelFor('publication');
  output.catalogs = publication.get('catalogs');

  return RSVP.hash(output);
},

...

output.catalogs = output.model.get('/api/ember/1/publications/' + output.model.id + '/catalogs');

...

var output = {
  model: this.modelFor("publication"),
  catalogs: model.catalogs,

...

this.get('store').findAll('catalog', {'publication_id': output.model.id, reload: true});

Could someone please give me a pointer to what I'm doing wrong / not doing please?




How do I make a file accessible at the top level root?

How do I make a file accessible at the top level root?

Basically, I want to be able to access foo.txt at https://www.sitename.com/foo.txt




mardi 11 décembre 2018

how to invoke function from helpers ember js

I am trying to call function and get the id of the radio button in ember js.




This is not calling the function in the controller. I tried another method but was getting error.




The error was : Uncaught TypeError: t.apply is not a function

The function is :

radiobuttonAction:function(e){
    if(e.target.checked){
        console.log("This is the id " + e.target.id);
    }
}

Could anyone help me with this and explain why my fuction in controller is not being called.

Thanks in advance. :)




lundi 10 décembre 2018

How to cache random results using Ember data?

Thanks to whoever is reading this and helping out. I'm going to describe what's already working, and then where I'm trying to get to (which I can't figure out):

What's working: In an EmberJS Component, there is a button that populates a textbox with a random string from a given collection of EmberData objects. The model() function queries for all of the objects from the API, and then the random_search() function picks a random one from the list and inserts it into the textbox. The code so far looks like this:

In componennt.js:

export default Component.extend({
  store: service('store'),
  model() {
    return this.store.findAll('randomsearchitem').then(function(items) {
      return items.map(function(item) {
        return {id: item.get('id'), funnnystory: item.get('funnystory')};
      })
    });
  },
  actions: {
    random_search() {
      this.model().then(function(items) {
        $('#searchbar-searchtext').val(items[Math.floor(Math.random() * items.length)]['id']);
        $('#searchbar-form').submit();
      });
    }
  }
}

In view.hbs:

<button onclick=>I'm Feeling Lucky!</button>

What I want: I would like to have:

  1. model() query for 15 random objects from the API and cache them locally, persisting between page loads. The API will potentially have a list of 1000's of them and I'd like to implement this logic client-side if possible. If this were SQL the query would look something like SELECT * FROM 'randomsearchitems' LIMIT 15
  2. random_search() to select one item, use it, and then discard it from the cache
  3. Once all 15 have been used once, I want to call the API again for a new list of 15 strings
  4. Uniqueness does not have to be enforced -- if the list of new objects contains an object that was present in the previous list, that's ok

Thankss




What could be reason of the error 'Maximum call stack size exceeded' inside Ember Data?

After Ember release new version 3.6.0 I started to get the error in console:

rsvp.js:24 Uncaught RangeError: Maximum call stack size exceeded at WeakMap.get () at getCacheFor (metal.js:25) at ComputedProperty.get (metal.js:2350) at Array.CPGETTER_FUNCTION [as []] (metal.js:752) at Function.jQuery.extend.jQuery.fn.extend (jquery.js:261) at Function.jQuery.extend.jQuery.fn.extend (jquery.js:282) at Function.jQuery.extend.jQuery.fn.extend (jquery.js:282) at Function.jQuery.extend.jQuery.fn.extend (jquery.js:282) at Function.jQuery.extend.jQuery.fn.extend (jquery.js:282) at Function.jQuery.extend.jQuery.fn.extend (jquery.js:282)

I figured out that reason of it store.query request in init in one of my components:

this.get('store').query('user', { 'filter': { 'type': '1', 'gender': 'male' } }).then(tutors => {
    this.set("tutors", tutors);
});

How to figure out a reason why I started to get this error?




dimanche 9 décembre 2018

"DEPRECATION: Upgrade ember-cli-inject-live-reload version to 1.10.0 or above" warning will not go away after upgrade

I am new to working on an Ember front-end site and just recently received a warning stating the following:

DEPRECATION: Upgrade ember-cli-inject-live-reload version to 1.10.0 or above

I went ahead and ran a npm audit fix and npm upgrade ember-cli-inject-live-reload. When I run npm show ember-cli-inject-live-reload version it says 2.0.1. So, when I re-run ember s, I get the same deprecation error. I tried closing and restarting VS Code, but that did not work. Does anyone know why this is happening and how I can fix it? Or, do I just ignore it?




Ember save data to store and display without having a server api

I have a users model which fetches data from github users api (https://api.github.com/users). While displaying the list there is a add button which should add the user to a shortlist section below and which has a remove button to remove user from shortlist. I don't have api to save shortlist data. What is the best approach to make this work?

Try 1: Created a shortlist model and used store.push

this.store.push({
    data: [{
        id: user.id,
        type: 'shortlist',
        attributes: {
        login: userData.login,
        avatar_url: userData.avatar_url,
        type: userData.type
        }
    }]
});

and used item.unloadRecord(); to remove from model. But did nor found a way to fetch all record and show as this.store.peakAll('shortlist') wasen't working.

Try 2: Used localstorage to add user to shortlist, display and remove but here it needs page reload to display the add/remove changes as i used setupController to get the items from localstorage.

Please suggest how to do this in best possible way.




samedi 8 décembre 2018

How to implement an Ember Simple Auth using an external redirect

Here's my workflow.

  1. User presses a login button.
  2. User is redirected to the API which redirects to a login page on a third party site (ADFS SAML).
  3. User authenticates there, is returned to the API which decodes the response, creates a user and a JWT token (both stored in a datastore), and then redirects the user to Ember with a ?token= query parameter.

What I'd like to do is work this in to a custom ember-simple-auth authenticator (and authorizer?) in order to take advantage of the niceness of session and Authorization headers from there on.

Currently I've hacked an authenticator to do just the redirect to the identity provider. The rest of the API workflow is working. And I'm catching the token in a route on the way back and populating a User resource via a call to the database. But I feel that I'm heading down the wrong (and the long) path.

Any thoughts? Is this something that ember-simple-auth-token is designed for?




jeudi 6 décembre 2018

Duplicate property array of models in component; Ember

If I have a store inject in a component property how can I duplicate it so that I can pass it through a promise validation.

I tried duplicating with

var models = this.store;
let models= this.store;
but when I set models in the validation function it only contains the model. If I used the wrong nomenclature let me know. I started a new job in Ember and they all use data filling through components.


How to add a class on Ember-bootstrap Modal?

I am using ember-bootstrap modal in which attribute "size" is "xl". xl takes my customized modal size class ".modal-xl". But I have another class ".modal-full" which adds more size to my modal-xl. How can I add this class="modal-full" on my

.modal-xl {
    @media screen and (min-width: $modal-xl) {
        max-width: calc(#{$modal-xl} - 2rem);
    }
}
// add option to bootstrap modal for full-width option
.modal-full {
    @include media-breakpoint-up(xl) {
        max-width: calc(100% - 4rem);
    }
}

Template file:


<table></table>


Anyone please help me with this. Thank you in Advance.




How to trigger didReceiveAttrs in Ember component

Using version 2.17. I have an Ember component inside an /edit route with a controller:

// edit.hbs


Inside my component, I am using a didRecieveAttrs hook to loop through ingredients on render, create proxy objects based off of each, and then build an ingredient table using those proxy objects.

// ingredient-table.js

didReceiveAttrs() {
  let uniqueIngredients = {};

  this.get('ingredients').forEach((ingredient) => {
    // do some stuff
  })

  this.set('recipeIngredients', Object.values(uniqueIngredients));
}

I also have a delete action, which I invoke when a user wishes to delete a row in the ingredient table. My delete action looks like this:

// ingredient-table.js

deleteIngredient(ingredient) {
  ingredient.deleteRecord();

  ingredient.save().then(() => {
    // yay! deleted!
  })
}

Everything mentioned above is working fine. The problem is that the deleted ingredient row remains in the table until the page refreshes. It should disappear immediately after the user deletes it, without page refresh. I need to trigger the didReceiveAttrs hook again. If I manually call that hook, all my problems are solved. But I don't think I should be manually calling it.

Based on the docs, it is my understanding that this hook will fire again on page load, and on re-renders (not initiated internally). I'm having some trouble figuring out what this means, I guess. Here's what I've tried:

1) calling ingredients.reload() in the promise handler of my save in ingredient-table.js (I also tried recipe.reload() here).

2) creating a controller function that calls model.ingredients.reload(), and passing that through to my component, then calling it in the promise handler. (I also tried model.reload() here).

Neither worked. Am I even using the right hook?




mercredi 5 décembre 2018

Emberjs: alternative rendering of an undefined attribute

I would love to control how an undefined attribute of a model is rendered. Perhaps undef. This would help in catching typos. Currently it's just rendered as empty string.

PS. Ideally, the ember-template-lint marked them as errors: https://github.com/ember-template-lint/ember-template-lint/issues/575




how to configure ember-cli-babel based on environment in ember-cli-build.js?

We are migrating our site to ember, so as of now we use ember as well as JSPs. Since in production, I have a polyfill loaded when my site loads, I want to use babel polyfill inside the ember app only on development and testing environment. I do not want it on production bulid. I know I can do the following

//ember-cli-build.js
let app = new EmberApp(defaults, {
  'ember-cli-babel': {
    'includePolyfill': true 
  }
}

I need something like the following to include polyfill based on the environment.

//ember-cli-build.js
let app = new EmberApp(defaults, {
  'ember-cli-babel': {
    'includePolyfill': this.ENV=='production' ? false:true 
  }
}




mardi 4 décembre 2018

Ember reloating belongsTo relationship

I have a belongsTo relationship defined in the model, e.g.

gallery: DS.belongsTo('store-gallery', { async: true }),

Later on, I'll create a new object and assign it to the relationship if it is null:

let galleryObject = this.get('store').createRecord('store-gallery', {}); this.set('gallery', galleryObject); console.log('Created', galleryObject, await this.get('gallery'));

The problem is that the this.get('gallery') call returns NULL due to Ember reloading the relationship.

How do I set the relationship (preferrably without having to convert it to non-async) without it immediately overwriting it?




lundi 3 décembre 2018

Determine which bindings caused computed property to update

Say I have a controller with a computed dependency tree like

a
  b
    c
      d
  e
    c
  f
    c

  • updating a should re-compute all properties
  • the bindings for c are b, e, f

How can I log out which binding caused a computed property to update? I want to do something like

const ctrl = Ember.Controller.extend({
  a: null,
  b: Ember.computed('a', foo),
  c: Ember.computed('b, e, f', function () {
    // did b, e, or f trigger this?
  }),
  d: Ember.computed('c', fizz),
  e: Ember.computed('a', buzz),
  f: Ember.computed('a', blah)
});

ctrl.set('a', 'foobar');
// => should see if b, e, or f was triggered last




Ember i18n Dynamic Text for a tag

I'm currently translating an application using ember's i18n library.

With the use of a placeholder, I'm able to translate text for a tag, nevertheless, I'm are only able to pass the tag to the placeholder if the text given is a string.

The tags we are using are normal i18n tags:

example_tag : 'ejemplo'

The method we have for the placeholder we have right now looks like this:

TranslationsPlaceHolder: (->{ 
    return Ember.I18n.t('example_tag');
})

and the way we call it is like this:



I'm currently looking for a way we can assign different tags with the use of one placeholder with dynamic tags, so we could pass the tag we want to translate as a parameter and only use one placeholder with different tags.

We are using reference from this question: Inserting a translation into a placeholder with Emblem.js

Thanks a lot!




dimanche 2 décembre 2018

Ember JSONAPI Adapter with Django REST framwork json API

I am using EmberJS with django. For my API do I want to use JSONAPI. For this I installed Django rest framework json api. And in Ember do I use the JSONAPIAdapter.

When my Ember app tries to get /appointments/ everything is fine and

"type": "Appointment"

but when my Ember Store tries to save an appointment it goes to the correct URL but

"type": "appointments"

after some testing I concluded that the only type that works is "Appointment", not "appointment" and neither "appointments" or "Appointments".

I don't know why the Ember JSONAPIAdapter does this, but is there a way to fix this problem?




Get the label of multiselect checkbox when selected

So i have a todos list and i need to add a checkbox for each todo and then to get the todo value when that checkbox is selected

My application.hbs

        
      <li class="list_shopping li_num_0_1">

                            <div class="col_md_3_list">
                                <div class="cont_text_date">
                                    <label class="container">
                                                       
                                        
                                        <span class="checkmark"></span>
                                    </label>
                                </div>

                            </div>
                        </li>
                        

My application.js

 export default Route.extend({
      newTodo: "",
      actions: {
        myChangeAction() {
          alert("hey");
        },
      model() {
        return this.store.findAll("todo");
      }
    });

Any ideas please ? I ve tried a lot of solutions but none of them worked https://guides.emberjs.com/v1.10.0/getting-started/marking-a-model-as-complete-incomplete/ https://ember-twiddle.com/b0e9cab25764e50c122ca482776bdae3?openFiles=routes.application.js%2C




samedi 1 décembre 2018

architecture question - using sub routes vs components

I am trying to build a UI with left side bar having filters and right side having actual filtered data. For loading data into the dynamic part of the UI(right side), which approach is considered better in terms of code quality and app performance ?

a) Use sub routes (for dynamic part of the UI) b) Use separate components that load their own data (for dynamic part of the UI)




Combining Ember REST Adapter with Django rest_framework ModelViewSet

I am creating an application that uses Ember and Django. For the backend of Django do I use rest_framework with the ModelViewSet as my view class. In the frontend with Ember do I use the RESTAdapter.

My backend sends data back like this:

{
    "id": 22,
    "name": "test",
    "startdate": "2019-01-01",
    "enddate": "2018-12-26"
}

while my frontend expects it like this:

{
  "appointment": {
    "id": 1,
    "name": "test", 
    "startdate": "2019-01-01",
    "enddate": "2018-12-26"
  }
}

I can't figure out how to make either end conform the other end in a nice and clean way. In the Django view class could I do this:

    def list(self, request):
        """Send all appointments."""
        serializer = AppointmentSerializer(self.queryset, many=True)

        return Response({'appointment': serializer.data})

and it would work to get the appointments, but then I would have to alter all the functions like create, update, delete etc. I feel like there has to be a clean and better maintainable way to fix this issue.




vendredi 30 novembre 2018

What is the best way to test an Ember component that has an outlet?

I want to test a component that has an with a handful of subcomponents that get loaded based on the URL. Currently, I simply render each component and test them individually. What are the performance implications of running this.render(hbs...) several times? Is there a better way to do this?




setupController is not working for hasMany data

here is my code. when a user has only 1 property code is working fine but in case of multiple properties. setupController and aftercontroller is not working

 model: ->
    return @get('session.currentUser.properties')

 setupController: (controller, model)->
     controller.set('properties', model)

user model is

Userr = DS.Model.extend(
  email: DS.attr('string')
  telephone: DS.attr('string')
  properties: DS.hasMany('property', { async: true })
)

`export default User`




Getting Ember frontend and Flask backend to communicate through separate Docker containers

I have dockerized a backend webapp built with Flask. The CMD line of the Dockerfile runs python app.py which internally calls app.run(host='0.0.0.0'), so that the app is running (within the docker container) at 0.0.0.0:5000. I then run the built container with

$ docker run -p 5000:5000 -it my-image:latest

The frontend is built with ember. Within the .ember-cli file, proxy is set to http://localhost:5000. When I run $ ember serve locally, the app runs smoothly at localhost:4200, communicating with the backend running from the docker image. However, I also want to run the frontend on a docker image (based on an apache image). My Dockerfile:

FROM httpd:2.4-alpine
COPY ./dist/ /usr/local/apache2/htdocs/
COPY ./.htaccess /usr/local/apache2/htdocs/

The .htaccess file is copied directly from Ember - Deploying (as per the Servers section):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.html [L]
</IfModule>

I then do the following:

$ ember b --prod  # build the app for production (stored in ./dist/)
$ docker build -t my-frontend:latest .
$ docker run -dit --name my-frontend -p 8080:80 my-frontend:latest

I then go to localhost:8080, and can see my app's loading wheel, which means this image is working in isolation. However, I continue to get 404 errors when it tries to access the backend.

What am I doing wrong that the containers can't communicate with each other?




Need a route called 'tests'

I have a legitimate need to generate a route called 'tests'. The problem is /tests is already being for the built in test runner. Can I reconfigure the test runner to use a different route?




Is it possible to have (an undefined number of) optional segments in the Ember router?

I would like to collect extra segments from the Ember router in an array. Here is a made-up path to illustrate what I mean:

this.route('group', {path: 'group/:group_id(/:segments[])*'}, function() {

Is it possible to use a request like this:

GET /group/123/some/path/segments

And have them collected in an array?

group.id = 123
segments = ['some', 'path', 'segments']

Or is there any way to define optional segments, so I can just add many and collect them manually?




mercredi 28 novembre 2018

then() returning a null value when it should be pending

Ember 2.17

I am calling an helper from my template :


  


line, as well as pricing are ember models.

The helper is as following :

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

export function pricingsFullPricing([pricing]) {
  pricing.then(
    p=>{
      debugger
    },p=>{

    }
  )
}
export default helper(pricingsFullPricing);

When I run the page, debugger is called twice (the template loop run once).

First time p is null, the second time it is a pricing.

Isn't then supposed to prevent that? Why does it behave like that?




Override application.hbs template in Emberjs

In emberjs, I am in a situation that my application already has routes template that uses the application.hbs template, but now I want to create a new route templates that doesn't use application.hbs.

Is there any easy solution for that?

I have seen many answers but that doesn't match my specification and also my version of ember is 2.11.

Thank you.




EmberJS Component - Run custom function after DOM has fully loaded

I'm struggling to fully grasp the component lifecycle. I've created a component, but I need my custom javascript function to run after the DOM is complete. I've scoured through the EmberJS Docs and Stackoverflow, but any documentation I come across doesn't work as I intended.

My Issue

I've attempted to use didInsertElement and didRender, but they still get called before my repeating elements have loaded in the DOM. How do I circumvent this to have my Javascript run after the DOM has fully rendered.

My Attempts

Below is an extremely stripped down and barebones example using an alert in place of my script. The desired outcome is to have this alert appear after the DOM is rendered, the below examples have it alert before.

import Component from '@ember/component';

export default Component.extend({

     didRender() {
        alert('didRender');
     },

     didInsertElement() {
        alert('didInsertElement');
     }
});

Thanks in advance.




mardi 27 novembre 2018

Is there any way to resolve Ember routes, controllers, components from custom directory?

Is there any way to resolve Ember routes, controllers, components etc from custom directory and fallback to default app directory when not found?




Separate Ember Addon from vendor.js file to a separate file

I'm using a "core"-addon which contains logic that is used in multiple "boilerplate" - ember applications, when I build a boilerplate-application, the addon code is added to the "vendor.js" file found in the "assets"-folder. Is there a way I can make this code build to a separate "my-addon-vendor.js" file?

My "core"-addon is linked to my "boilerplate"-project using "npm link my-core-addon".

Thanks in advance

Versions:

  • Ember Version: 3.5.0
  • Ember CLI: 3.5.0
  • Node: 8.11.3
  • npm: 5.6.0



Spring Boot + Spring Security + Ember JS

I have a Spring boot application using Spring security for authentication.

SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .csrf().disable()
        .formLogin()
            .loginProcessingUrl("/authenticateTheUser")
            .permitAll()
        .and()
        .logout().permitAll();
}

The users are authenticated based on the values in database. I am using BCrypt password encoder for encoding passwords.

When I access the API's it is working correctly. It authorizes when a request is made.

Now I am stuck with linking my spring boot app with Ember JS. When I try to call the /authenticateTheUser method it says invalid cors request.

Can someone help me in getting it solved. Should we use any addons for authorization with Ember JS to call the default login method provided by spring security




lundi 26 novembre 2018

Emberjs dynamic inject from mixin

I have a lot of controllers using difference services,where I should extend one mixin. In mixin, based on the controller's call I should inject difference service. Is it really do ? If yes, I open to any suggestions. My controller look like this:

import FilterController from 'core/addon/filter/filter-controller';
import defaultMixin from 'default-mixin';

export default FilterController.extend(defaultMixin,{
  filter: Ember.inject.service(Pathes.inject.service.leaseFilter),
})

Mixin:

import Ember from 'ember';
import Views from '../const/views';
import ViewsService from '../static-services/views';

const {
  computed,
} = Ember;

export default Ember.Mixin.create({

##THIS VIEW SERVICE I SHOULD INJECT BASED ON CONTROLLER ##VIEW.INJECT.SERVICE.[LEASE,LEASE1,LEASE2,LEASE3]

  viewService: Ember.inject.service(Views.inject.service.Lease),

  defaultViewType: computed(
    'viewService.filteredViewsList',
    function () {
      const viewList = this.get('viewService.filteredViewsList');
      return ViewsService.getDefaultViewFromList(viewList);
    }
  ),
});




Using Etags with ember-data

I am trying to implement some client side caching via etags and last modified headers; however, ember-data doesn't seem to be using the etags for the ajax requests. I only get 200 responses and never a 304. I don't see any ETag header being sent with the request headers.

When I make the ajax request multiple times directly from the browser address bar, I'll get 304 not modified responses after the first request, so I know the server is sending things back correctly.

Is there a configuration I need to set up to make this happen?

This is a CORS request, but I think that I have and I have exposed the ETag header:

Access-Control-Expose-Headers: ETag and the Etag header is sent back with the response.




How to authenticate against Twitter with Ember Torii and Ember Simple Auth

I'm trying to authenticate against Twitter using Ember Torii and Ember Simple Auth. However, I'm not sure how to properly close the authentication popup once the user has been authenticated. My code:

//app/authenticators/torii.js
import {inject as service} from '@ember/service';
import Torii from 'ember-simple-auth/authenticators/torii';

export default Torii.extend({
  torii: service(),
  ajax: service(),

  authenticate() {
    const ajax = this.get('ajax');
    return this._super(...arguments).then((data) => {
      console.log('Authorization data:');
       console.log(data);
      if(data.provider === "twitter" && data.code) {
        return {
          accessToken: data.code,
          provider: data.provider
        };
      }
      //This is for OAuth2 providers e.g. Facebook
      return ajax.request(
        'http://localhost:8080/api/1/auth', {
        type: 'POST',
        dataType: 'json',
        crossDomain: true,
        contentType: 'application/json',
        data: {'provider': data.provider, 'authorizationCode': data.authorizationCode}
      }).then((response) => {
        return {
          accessToken: response.token,
          provider: data.provider
        };
      });
    });
  }
});


  //config/environment.js
  .......
  providers: {
    'facebook-oauth2': {
      apiKey: 'xxxxxxxxxxxxxx',
      scope: 'public_profile,email'
    },
    'twitter': {
      requestTokenUri: 'http://localhost:8080/api/1/auth/twitter/'
    },

//app/torii-providers/facebook-oauth2.js
import { computed } from '@ember/object';
import FacebookOauth2Provider from 'torii/providers/facebook-oauth2';

export default FacebookOauth2Provider.extend({
  redirectUri: computed(function() {
    return [
      window.location.protocol,
      '//',
      window.location.host,
      '/torii/redirect.html'
    ].join('');
}),

  fetch(data) {
    return data;
  }
});

From my understanding, the following happens in case of authentication using Twitter:

  1. User clicks on an UI element to initiate the authentication flow. Ember Torii creates a popup and does a GET request to requestTokenUri. The API back-end generates the oauth_token required by Twitter and redirects to Twitter login page with oauth_token as query parameter.
  2. The user logs in. Assuming a successful login, Twitter then redirects the browser popup to the configured Callback URL on the API backend along with oauth_token and oauth_verifier parameters.
  3. The back-end API's Callback URL receives these parameters and exchanges these for oauth_token and oauth_token_secret that are stored in the back-end.

My question is basically, what happens next and how to cleanly and securely close the pop-up and initialize the session:

My back-end converts the token generated in 3 above to an internal JWT token and re-directs the browser pop-upto torii/redirect.html?code=<<JWTTOKEN>>. However, when the browser pop-up closes, Torii tries to re-authenticate the given token by calling authenticate method, which is not required. I've put in a workaround as show above in app/authenticators/torii.js. Is this correct? Is there a better way?




Ember - Sort Model after findAll

I'm using Emberfire in my app, and I'm trying to findAll stats, and then sort that model by a key, like in the following example. But, when I sort this way I lose the ability to see real time updates in my template and I have to reload the page to see the new/updated data in the view.

 model() {
    return this.store
      .findAll('stats', {
        reload: true,
        backgroundReload: true
      })
      .then(stats => stats.sortBy('date'));
  }




Parameters nested in `_jsonapi` when sending from Ember

I have an Ember 3.5 application that is connected to a Rails API app which uses the jsonapi-rails gem.

I'm using the default ember store:

// app/adapters/application.js
import DS from 'ember-data';

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

And I have a simple route for a user registration form:

// app/router.js
import EmberRouter from '@ember/routing/router';
import config from './config/environment';

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

Router.map(function() {
  this.route('users', function(){
    this.route('user', { path: '/:user_id'});
    this.route('new');
  });
});

export default Router;


But when I attempt to save a record the params are unexpectedly nested in an _jsonapi key on the Rails backend:

app/controllers/api/v1/resource_controller.rb:75:in `permitted_attributes'
app/controllers/api/v1/resource_controller.rb:63:in `create_params'
app/controllers/api/v1/resource_controller.rb:21:in `create'
Started POST "/api/v1/users" for 127.0.0.1 at 2018-11-26 19:20:37 +0100
Processing by API::V1::UsersController#create as JSON
  Parameters: {"_jsonapi"=>{"data"=>{"attributes"=>{"email"=>"test@example.com", "password"=>"[FILTERED]", "password-confirmation"=>"[FILTERED]"}, "type"=>"users"}}}
Completed 400 Bad Request in 2ms (ActiveRecord: 0.0ms)

This is really puzzling since the request payload in Chrome is:

{"data":{"attributes":{"email":"test@example.com","password":"p4ssword","password-confirmation":"p4ssword"},"type":"users"}}




Spring Boot with Spring security + Ember JS

I have an Ember application that uses API's created using Spring Boot. I have implemented spring security for authentication in spring boot. I dont know how to link Spring Boot and Ember js now. Can someone help me through it?




dimanche 25 novembre 2018

emberjs model reverse relationship unclear

I have a postal_address model that includes: street, zipcode, city, etc. I then have multiple unrelated models like Organization or User that have the postal_address as one of their attributes. The using-models simply refer to the postal_address as belongsTo, specifying the reverse is not clear to me, i.e. inside of the postal_address do I indicate anything in terms of models that refer to it?

Depending on the context, updating the address may affect the Organization, other times the User. There are many more models that could use the postal_address than the two I listed, in the event one suggests to duplicate the address-model per use-case.




samedi 24 novembre 2018

How does Ember Data deal with security of cached objects?

From what I understand, ember data is a memoization engine; invoking peekAll looks for cached data rather than making an expensive network call. But where are these data cached? If these data are loaded client-side, doesn't that mean the data is "in transit"? If I want to design a secure front end application that holds sensitive data for the least amount of time, how can I do this? Should I avoid using Ember data entirely and simply force back end calls to be made?




vendredi 23 novembre 2018

Ember build faield because of broccoliBuilderError

I'am on an ember project and I am trying to upgrade ember version from 2.8 to 3.5.0. But since I changed the version and also some several dependencies version I get this error :

enter image description here

I've tried to fix this with ember-cli-build file but the error persiste.

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

module.exports = function(defaults) { const isPublicEnv = EmberApp.env() === 'public';

const app = new EmberApp(defaults, {

    'sassOptions': {
        includePaths: [
            'bower_components/materialize/sass',
        ],
    },
    'outputPaths': {
        app: {
            css: {
                design1: '/assets/design1.css',
                design2: '/assets/design2.css'
            },
        },
    },
    'ember-cli-babel': {
        includePolyfill: true,
    },
    'minifyJS': {
        enabled: isPublicEnv,
    },
    'minifyCSS': {
        enabled: isPublicEnv,
    },
    'fingerprint': {
        enabled: isPublicEnv,
    },
    'tests': !isPublicEnv,
    'hinting': !isPublicEnv,
    'sourcemaps': {
        enabled: !isPublicEnv,
    },
});

app.import('vendor/lib1.js');
app.import('vendor/lib2.js');

return app.toTree();

};

Any suggestion to resolve this ?




jeudi 22 novembre 2018

Even after refresh some attributes in the model are not changed

I am new to EmberJS, and facing problem with model data updation

Controller :

export default Ember.Controller.extend({
queryParams: ['jobid'],
jobid: null,
currentCount: null,

actions: {
 onOffToggle(e) {
  var isChanged = this.get('model.b.isChanged');
  this.set('model.b.enable', e.target.checked);
  this.set('model.b.isChanged', !isChanged);
  console.log(this.get('model.b.isChanged'))
},
iterationCountChange() {
  var currentCount = this.get('currentCount');
  var isCountChanged =
      (currentCount != this.get('model.b.count')) ? true : false;
  this.set('model.b.isCountChanged', isCountChanged);
}
}});

Route:

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

beforeModel: function (transition) {
this.jobid = transition.queryParams.jobid;
},
model(){
  return Ember.RSVP.hash({
    a:   this.store.queryRecord('a', {jobid: this.get("jobid")}),
    b: this.store.queryRecord('b', {id: this.get("jobid")})
 });
},
setupController: function(controller, model) {
  this._super(controller, model)
controller.set('currentCount', model.tunein.get('iterationCount'))
},

actions: {
 paramChange(a, b)
  Ember.$.ajax({
    url: "/rest/test",
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
       b: b,
       a: a
     })
   }).then(response => {
    this.refresh();
  })
},
error(error, transition) {
  if (error.errors[0].status == 404) {
    return this.transitionTo('not-found', { queryParams: {'previous': window.location.href}});
   }
  }
 }
});

Here in controller I am keeping track if some value have changed, and if they have changed then update the flag related to their change, these flags like isChanged and isCountChanged are the part of the model's data, after user cliks submit button , paramChange action is called and then a post call is made to update the db for respective property changes, and then this.refresh() is called to render the latest model data.

But the problem is, once isChanged and/or isCountChanged are changed from their default value, then they don't reset to the new value present in the model data, e.g. after refresh the value to both these flags should be reset to false but it comes always true, I checked the value in the setUpController hook for the values of these flags and it confirms to true.

According to me it has something to with the controller, since any value which is used in controller once is not resetting to new value coming after refresh.

Kindly help I am spent a lot of time in this and got nothing till now, do inform if any extra information is required.




In ember, how to change values of checkboxes based on another

I have four checkbox and I want to check automatically checkbox with id = 2 if checkbox with id = 4 is checked.

I did the following but did not get the output. Could someone help me with this.

{#each category in checkboxList}}
            
            
                
            

The checkboxList is

[
   {"IS_CHECKED":false,"CHECKBOX_ID":1}, 
   {"IS_CHECKED":false,"CHECKBOX_ID":2},
   {"IS_CHECKED":true,"CHECKBOX_ID":3},
   {"IS_CHECKED":false,"CHECKBOX_ID":4}
]




In ember, how to change values of checkboxes based on another

I have four checkbox and I want to check automatically checkbox with id = 2 if checkbox with id = 4 is checked.

I did the following but did not get the output. Could someone help me with this.

{#each category in checkboxList}}
            
            
                
            

The checkboxList is

[
   {"IS_CHECKED":false,"CHECKBOX_ID":1}, 
   {"IS_CHECKED":false,"CHECKBOX_ID":2},
   {"IS_CHECKED":true,"CHECKBOX_ID":3},
   {"IS_CHECKED":false,"CHECKBOX_ID":4}
]




How to handle non-model data in ember

I want to retrieve tabular data related to a model and display it in a table. I am not sure how to do that in ember. Here is what I tried :

I added a get action on my API that return a json with the data

model_path\:id\related_data

I added a custom action to the model :

allShares: modelAction('all_shares',{type: 'GET'})

ANd here is how I add it to the route's model :

allShares: invoice.then((i)=>{return i.allShares()})

Now I have a model.allShares that should contain the data. In the network inspector I can see that there has been a query to the endpoint returning the JSON data I want to display.

The following code in the view is totally blank :


              
              
            

I can now see a big object in the inspector (using debugger in model()) and I am not sure what to do of it, or even what type of object is it.

WHat can I do now to handle this data?




mercredi 21 novembre 2018

Sort Ember Object Array with Promises

I have a model model/person

{

  firstName: DS.attr( 'string'),
  lastName: DS.attr( 'string'),
  email: DS.attr( 'string' ),
}

and another model model/project

{

  name:            DS.attr( 'string' ),
  code:            DS.attr( 'string' ),
  startDate:       DS.attr( 'date' ),
  endDate:         DS.attr( 'date' ),
  users : DS.hasMany('person', {async: true}),

}

then i'm retrieving all the projects with as an array which contains ember objects. since the project -> users is async its a promise. and i want to sort that array using the first name of the person. when the data is arrived accordingly and re render the hbs that is using the list

i have a computed property called

renderProjects = computed ('model.projects.[]')
{
 // trying to sort in here but data is not avaiable so its not getting sorted
}




Ember & Cypress | Integration test failing likely due to lack of store context

I am working with Ember.js on the frontend and using Cypress.io for integration testing. I have a "Order Status" button that upon click is supposed to use data within the store to access the specific order and navigate to the Order Status page.

However within the test, upon click from the modal, the Order Status page cannot load and my test throws this error in the console, which I think likely has to do with that route's model not finding the order from within the store and loading.

In the Cypress test, I've created the necessary routes to pass in session data, but am struggling to understand if the lack of store data is throwing this error and how to fix. Important to note that this whole flow 100% works, I'm just trying to get test coverage.

I'll attach snippets from the relevant files / functions below -- please do let me know if more information is needed. I really suspect that Cypress cannot access the Ember store, but after much research and experimenting not exactly sure what the issue is. Thanks so much for your help :)

order-status.js - model function from route

async model({ order_id: orderId }) {
    let cachedOrder = this.get('store').peekRecord('order', orderId);
    return cachedOrder
      ? cachedOrder
      : await this.get('store').findRecord('order', orderId);
  },

modal.hbs - where we navigate from current page to order-status route

<fieldset>
  <span class="modal-text">See order status</span>
  <div class="inline-button-wrap">
    <button 
       
      class="close-btn button-hollow-green">
        Close
    </button>
    <button 
       
      class="order-status-btn">
       Order Status
     </button>
  </div>
</fieldset>

test.js - test that simulates clicking order status button above

it('order status btn navigates to order status page', () => {
  cy.server();
  cy.route('GET', '/api/session', sessionResponse);
  cy.route('GET', `/api/orders/*`, order);
  cy.visit('/');
  cy.get('.delivery-card .button-cta').click(); //opens modal 
  cy.get('#modal .order-status-btn').click(); //navigates to order-status
});



Ember-cli-build, exclude components ember addon

I'm using a "core" ember addon in a boilerplate, with

npm link core-addon

This addon contains generic components, helpers, routes...

Is there a way to exclude some of these components in the boilerplate's ember-cli-build file?

I already tried the following in the ember-build-cli in my boilerplate project, which is probably wrong:

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const environment = EmberApp.env();
module.exports = function (defaults) {
    let app = new EmberApp(defaults, {
        funnel: {
                enabled:true,
                exclude:['core-addon/pods/components/pages/**/*']
            },
    });
return app.toTree();
};

Ember version: 3.5.0 Ember cli version 3.5.0 node version 8.11.3




mardi 20 novembre 2018

Why can't I iterate over a list of Firebase Img URLS, but can access each on individually?

I have an array of Firebase storage URLs that link to images like so:

[
"https://firebasestorage.googleapis.com/v0/b/xyz-app-1540127382149.appspot.com/o/images%2F-LR855-bwb_IuYAFeYlf%2Fyyz-1.jpg?alt=media&token=e39d4dd0-6821-477a-b165-4ead2eb0a8c4",
"https://firebasestorage.googleapis.com/v0/b/xyz-app-1540127382149.appspot.com/o/images%2F-LR855-bwb_IuYAFeYlf%2abc-1.jpg?
]

Paste these into a browser? Works. Get single item in array and add it to an img element src? Works.

Iterate over the array and try to add each to an img element src? Stack Error.


  <div class="carousel-item active">
    <img
      class="d-block w-100"
      src=
      alt="Post Image"
    >
   </div>
 

stack: "Error: Assertion Failed: fullName must be a proper full name

I don't get it. Why can I get a single link in the array and it will display, yet when I iterate over the list I get an error..?




How to use hotjar with ember ?

I need to use hotjar for work, but i have some difficulties to set it up. The project is an ember project, and i have found this project to integrate hotjar : https://github.com/byrnedo/ember-hotjar

In this github page, it says : "in routes and controller you will have _hj.push available", but i can't manage to make it work and i can't find any information about how to set it up.

I added this in config/environment.js :

hotjar: {
  id: my-id
},

And in a route, if i do this :

console.log(this.get('_hj'))

I get this result in the console :

ƒ () {
    (window.hj.q = window.hj.q || []).push(arguments);
  }

Meaning that hotjar is successfully installed, but when i'm trying to something like :

this.get('_hj').push('trigger', 'hello_world');

An error appears saying :

Uncaught TypeError: this.get(...).push is not a function

Does anyone know how to make it work or if i'm making something wrong ?




lundi 19 novembre 2018

EmberJS: Some errors not thrown in production

Recently I encountered a scenario where an error (Assertion Failed: calling set on destroyed object) was thrown while running my app in development mode, but the same error wasn't thrown in production.

Why is it so? Is there a justification? If I'm missing, what other differences between production and development mode should I know?




samedi 17 novembre 2018

Ember Disable button while an action is completing its process

template


<button  type="submit">Add</button>

controller

export default Controller.extend({
    actions: {
        addUser: function(){
            //some codes here
            $.ajax({
                //some codes here
            }).then(()=>{
                alert("success");
            });
        }
    }
});

When I call press the button and call the function addUser I need to disable the button until the whole function is finished execution

Please help..!




vendredi 16 novembre 2018

Ember: Send child component's action to a parent component

I am trying to call/trigger a child component's action from a parent. I've tried this a couple ways but I'm not getting anywhere. This is basically what I have so far.
I am attempting to send the action up to the parent by passing it as a parameter in the action that was passed down...
This seems a bit like a spaghetti situation but the way my project is organized, this is my result.

If anyone could, please tell me how to successfully pass an action up to the parent as a parameter. (I'm curious to know how, if possible)
If anyone also has a better suggestion on how to call a child's action, please share. Thanks in advance!

parent-component.hbs


<div onclick=></div>

parent-component.js

actionPassedFromChild: null,
....
actions: {
    parentAction(childAction){
       this.set('actionPassedFromChild', childAction);
    }
}


child-component.hbs

<div onclick=

child-component.js

....
actions: {
    anAction(){
       this.parentAction(childAction);
    }
    childAction(){
       //Some operation
    }
}

In this example, if I stop the code inside of 'anAction', I do have 'childAction'. But by the time that it gets passed into 'parentAction', it is undefined. Could anyone explain why?




Ember passing arguments to action using helper.

Let's take this case

  

In this case, value will be passed as an argument to the action "UpdateFirstName".

Now i want to pass an object "Person" also to the action. How do i do it?

I've tried

  

but no use. Can someone help?




Re render a component from another component Ember

I'm trying to re-render a specific component when another component is clicked. When the user clicks the particular button component, a variable in sessionStorage changes, which is used by another component to display data. Upon click I want that specific component to re-render itself. I have seen Ember Re-render component and Ember Rerendering component within component, but they don't seem to be working in my case. Here are my files:

templates/components/buttons/button-cancel.hbs


  
  <button class= > Accounts </button>
  



components/buttons/button-cancel.js

import Component from '@ember/component';
import MD from "../../utils/metadata";

export default Component.extend({
  init: function() {
    this._super(...arguments);
    this.metaData = MD.create().getMetaViewStuff("Leads", "record", "buttons");
    //    console.log(this.metaData);
  },
  actions: {
    changeToAccounts: function() {
      sessionStorage.setItem('module', "Accounts");
    }
  }

});

templates/components/panels/list-panel.hbs

 <!--This button is same as button-cancel-->




components/field-list-headers (the component that needs re-rendering)

import Component from '@ember/component';
import MD from "../utils/metadata"

export default Component.extend({
  init: function(){
    this._super(...arguments);
    this.metaData = MD.create().getMetaViewStuff(sessionStorage.getItem('module'), "list", "panels")
  }
});

function getMetaViewStuff

  getMetaViewStuff: function(module, submodule, item, i18n) {
    if (this.modules[module]["views"][submodule]["meta"] !== undefined && this.modules[module]["views"][submodule]["meta"][item] !== undefined) {
      let meta = this.modules[module]["views"][submodule]["meta"][item];
      return meta;
    }
    return false;
  }




jeudi 15 novembre 2018

Eslint in Visual studio code not working with .hbs files?

Ive got eslint installed in visual studio code and it works for .js files but with Ember's .hbs files no errors are shown in the code editor. I have it all enabled along with eslint packages installed. I am running Version 1.29.0.




Using React js inside an Ember project and importing a library using import from 'npm:

I've seen many other posts with a similar issue but I couldn't find any valid solution to my case.

A bit of background:

I'm working inside an Ember application, where React is being used to develop new components (we are replacing the old ember code, using React).

So far everything works fine and we are able to create and use React components inside Ember without any issues.

Problem:

One of the React component I'm writing needs to use a range date picker and I've found several utilities that do that. I've deleted all the unnecessary code from the component:

import React from 'npm:react';
import DayPickerInput from 'npm:react-day-picker/DayPickerInput';

export default class ContractDetails extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <DayPickerInput/>
      </div>
    );
  }
}

Every time I try to render it I get the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

Reading the other posts, I tried to replace:

import DayPickerInput from 'npm:react-day-picker/DayPickerInput';

With:

import {DayPickerInput} from 'npm:react-day-picker/DayPickerInput';

But I get a similar result (note the error now says it's getting an undefined rather than an object):

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `ContractDetails`.

The only thing that prevent the error to appear is to use:

<DayPickerInput.default/>

Which, however, causes issue with the library css.

I've tried to replace this library with many others but I always get the same error, so I'm excluding an error within the library itself.

Do you have any clues why I'm getting this error?

I'm using the latest react version (16.6.3)




Ember data model explicit inverse relationships

I’m struggling with explicit inverse relationships: https://guides.emberjs.com/release/models/relationships/#toc_explicit-inverses.

If 4 instances of the blog-post model can be associated with a comment (onePost, twoPost, redPost, bluePost), how come the inverse is set on the class definition of the blog-post and not at an instance level?

Surely all instances that are created from that model definition now will now be inverse to redPost? How do I create, say, a blog-post that I would like to be associated with the comment's bluePost attribute?

The closest answers I've found are Ember - Understanding Inverse Relationships and Setting the inverse option dynamically/conditionally in ember-data? but the first one oversimplifies the problem as to not be a relevant answer and the second one went unanswered.

Thanks in advance.




mercredi 14 novembre 2018

Cann't start ember server

I tried to run npm install for an old ember project and it stops with the error npm ERR! 404 Not Found: @myFile/zf-ember-notification@1.0.1 I am just starting with ember, can someone explain how can I open and edit old ember projects.




Iterating through key-values in ember.js handlebars template

I have a javascript object

this.attributes = {
            key: value,
            // etc..
        }

I would like to iterate through it and output key:value

Here is my solution:

import Ember from 'ember';

export default Ember.Component.extend({
init() {
    this._super(...arguments);
    this.attributes = {
        'SKU': '123',
        'UPC': 'ABC',
        'Title': 'Hour Glass'
       }

},

ProductAttributes: Ember.computed('attributes', function() {

    var attribs = this.get('attributes');
    var kvp = Object.keys(attribs).map(key => {
        return {
            'attribute_name': key,
            'attribute_value': attribs[key]
        };
    });
    return kvp;
})});

The template I came up with:


     : 


I am not happy with this solution since it looks cumbersome: first I convert object into an array of auxiliary objects with non-dynamic keys attribute_name and attribute_value, and then I references non-dynamic names directly within my template.

It works fine but is there a better way of doing this?




How can I see what request is done by Ember FastBoot?

I've installed ember-cli-fastboot and a certain path throws an Error: The adapter operation was aborted server-side (i.e. in the terminal).

Can I output all requests fastboot does, so I can see what the last one was before the rendering of the page was aborted due to this error message?




Why can't I set persistence even though login functions work with Firebase?

I have a component with a form that holds the email and password. Imports at the top:

import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import * as firebase from 'firebase';

Next, I inject the service for the firebaseApp and session (session just has some attrs that I set to tell the app we're authenticated -- these will be refactored later):

session: service(),
firebaseApp: service(),

If I pass these values into the signInWithEmailAndPassword() function from fbApp.auth(), the account is validated and logged in. Works as expected:

login() {
  const session = this.get('session');
  const fbApp = this.get('firebaseApp');
  const e = this.get('form.email');
  const p = this.get('form.password');

  fbApp.auth().signInWithEmailAndPassword(e, p).then(u => {
    session.set('user.email', u.email);
    session.set('user.signedIn', true);
    this.get('goHome')(); // route transition to home
  }).catch(e => {
    this.set('error', 'Something went wrong. Try again?');
  });
}

Next, I wanted to persist the session so that the user is not logged out on refresh, only if the tab is closed. So I modified the code and wrapped the signInWithEmailAndPassword in with setPersistence as follows:

login() {
  const session = this.get('session');
  const fbApp = this.get('firebaseApp');
  const e = this.get('form.email');
  const p = this.get('form.password');

  fbApp.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
              .then(()=> {

    fbApp.auth().signInWithEmailAndPassword(e, p).then(u => {
      session.set('user.email', u.email);
      session.set('user.signedIn', true);
      this.get('goHome')(); // route transition to home
    }).catch(e => {
      this.set('error', 'Something went wrong. Try again?');
    });

  }).catch(e => {
    this.set('error', 'Something went wrong. Try again?');
  });
}

This doesn't work. I get a Cannot read property 'SESSION' of undefined error in the console. I'm sure it has to do with how firebase is imported but I'm having trouble with it.




Ember js Disconnect Outlet doesnt clear cached template data

i have a modal where i open and via a outlet so opened it using following code

this.render( controller, {
  into: 'application',
  outlet: 'modal'
} );

then in the modal view i have a computed property

  peopleArray: computed ('someDataFromaMixin' , function (){
    debugger;
    return this.get( 'someDataFromaMixin' )
  }),

then i close the modal using below code

removeOutlet: function( ) {

    return this.disconnectOutlet( {

      outlet: 'modal',
      parentView: 'application'
    } );
  },

issue is the computed property compute if i go there with a page refresh

if i close the modal and re-open again the computedProperty will not trigger ( even if i modified the computed property data )

im clueless what cause this issue




mardi 13 novembre 2018

Rendering a component programmatically (not via template)

I'm working on an Ember app that's integrated with a separate SDK that has its own custom UI components. For example,

<integration-name-customer-view customer-name="Bob">

These components have render lifecycle hooks, like onRender, onCreate, etc.

I would like to hook into the onRender callback and insert an Ember component I have created (a tooltip with some special functionality).

Here's what I've attempted:

Integration-Customer-Name Definition

import MyTooltip from 'ember-app/components/my-tooltip';    

...

onRender() {
    let parent = this;

    MyTooltip
        .extend({
            layout: myTemplate,
            didRender: () {
                parent.appendChild(this.element);
            }
        })
        .create({ position: 'above' })
        .appendTo(document.body);
}

Now, this actually works, but I have two questions:

  1. Is this the right thing to do? Is there a simpler way/is this going to crash and burn?
  2. My template has a block in it. Is there a way to programmatically determine what is going to be rendered into that block?



how to include images to ember cli

i am doing a project using ember js as frontend.need help adding image.

for eg: in the template I want to add an image like

<img src="/location/image.png"/>

Where should I store the image? Is there any standard practices that follow in ember to store images and fonts?




Ember: Why does computed not fire when the observer does?

I'm having difficulty wrapping my head around this - I'm working with inherited legacy code, and while this seems like it should be very simple, it's anything but.

In this app/pods/application/route.js, there's a "welcome pack" object that's grabbed by the server, as part of that, there's a setWp() method called on the welcome-pack service, which sets the 'wp' value on that same service. (Yes, I know you can probably set the value on the service directly, with "this.wp.set('wp', welcomePack)" but as I said: inherited legacy code.) Point is, that should trigger the change in the value. My observer for wp.wp is firing, but NOT my computeds based on wp.wp. Any clues?

// app/pods/application/route.js
wp: inject('welcome-pack'),
model(){
  return this.store.findAll('welcome-pack').then((welcomePack) => {
  this.wp.setWp(welcomePack);
})
}



// app/pods/welcome-pack/service.js
import Service from '@ember/service';
export default Service.extend({
  wp: null,
  setWp(wp){ // <-- called when the model loads from the ajax request
    this.set('wp', wp)
  }
})

// app/pods/application/controller.js
import Controller from "@ember/controller";
import { inject } from "@ember/service";
import { computed, observer } from "@ember/object";

export default Controller.extend({
  wp: inject("welcome-pack"),
  init(){
    console.log('this.wp', this.wp) // <- logs service as class
    console.log('this.wp.wp', this.wp.wp) // <-logs null
    setTimeout(() => {
      // set for after the ajax call has been made and setWp() has been called. 
      console.log('this.wp', this.wp) //<- logs service as class
      console.log('this.wp.wp', this.wp.wp) //<- logs object as class
    }, 2000)
  },
  obsWPChanges: observer('wp', function(){
    console.log('wp changed'); // <-- never executes (don't expect it to)
  }),
  obsWPWPChanges: observer('wp.wp', function(){
    console.log('wp.wp changed') //<-- executes (as expected) when setWP() is called
  }),
  primaryColor: computed("wp.wp", function() {
    console.log("this.wp.primaryColor", this.wp.primaryColor) // <-- does not execute
    return this.wp.wp.primaryColor || "#37b3c0";
  }),
  secondaryColor: computed("wp.wp", function() {
    return this.wp.wp.secondaryColor || "#38a0d0"; // <-- does not execute
  })
});