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.