mardi 30 avril 2019

Data on Route not reloading / refetching from API

Say I have index and edit routes. From index, I selected item and redirected to edit route. Then when I change data on form field on edit route and click the back arrow on my browser, the changes made reflected on index which should not because save button was not clicked.

But when index route is refreshed the changes made don't reflect which is right. Now how could the index route reload the data without refreshing the page.




Does my remote server (Amazon EC2) need 2 different servers running to run EmberJS and Spring Boot?

It seems that for EmberJS we need a server to run, usually on localhost:4040.

Spring Boot needs its own server for run of coarse on localhost:8080.

Is this really necessary to run 2 different servers on a remote server or even recommended?

Why can't I just get the javascript from the EmberJS and put it in my Spring Boot project. As in go to the static resources folder and put the EmberJS files there?

Why do we really need a server for EmberJS in the first place? It's front end code to be read by a browser?

If none of this is recommended then how do we use EmberJS and Spring Boot together on one server? Everywhere I see uses EmberJS on its own server and does a cross request to localhost:8080 for spring boot.

I am relatively new to Web App Dev so some jargon may go over my head.




How to fix "Unexpected end of JSON"

I had my users page displaying users but then when I stopped working on the code for a while and came back to it I am getting an error which says "Error while processing route: users Unexpected end of JSON input SyntaxError: Unexpected end of JSON input" and also "Uncaught SyntaxError: Unexpected end of JSON input"

I don't know where to start on trying to fix this issue.

Here is the front-end code in the route file users.js:

model() {
    return this.get("store").findAll("user");
  },

Here is the api code in the users controller:

# GET /users
  def index
    render jsonapi: User.all
  end




Can I use Deno with Ember-Cli?

I recently found Deno and I am very interested in using it with my Ember-CLI projects. I know Deno is still very unstable, but I would like to know if at this point it would be advisable to attempt to migrate from node to deno for even a small project. I couldn't find information about progress in that direction and I want to start working on it.

Is this possible, because I don't think my code can compile right now?




lundi 29 avril 2019

Send POST request from ember to specified URL

I am new to full stack development, and having an issue with a web application I'm working on for my employer. I was tasked with creating a fairly simple application that we can scale over time. For now all that it needs to do is take data from one of our databases, and pass it to a front end application. Using this front-end app our workers should be able to double check the information passed in, and make sure it has been properly translated to a new format. After it is translated I want to send an HTTP POST request to our new systems back-end and have it add this new data via the REST API. Essentially it's an application that was used for practice to get me more acquainted with full stack development while making an effective tool to transfer mass data from one system to another. I can't seem to figure out how to set up something in ember.js to send that POST request to somewhere other than my back-end though.




How to customize paper-select component?

I need to customize paper-elements like paper-select and paper-select with search, but don't really know is it possible and if so how exactly to do it.

I tried this https://ember-power-select.com/docs/styles/, but doesn't work (yes, we have scss). I tried the same example as on the link and instead of a blue border it created a grey one. And for sure this grey border isn't related to the

$ember-power-select-border-color: #64A5ED;

selector in app.scss, because the same grey border appears for this import along:

@import 'ember-power-select';

without any selectors at all. One of the task is to move placeholder from center to the left corner of the input. But ::placeholder { flex: left } does not work. Also I don't have strong computer science background, so I would highly appreciate if you explain this as simple as possible.




dimanche 28 avril 2019

Computed property is only firing once

I have a service called screen-size which has a property called width. This property is the value of the window width and will update on a resize event.

This works fine. In a component, I have a computed property that I want to update when this value changes like so...

nameStyle: computed('screenSizeService.width', function()
{
    console.log('in computed');
    return this.getFontSize(2.5, 2, null, null, this.$())
}),

This is only running once at the beginning unless I do this...

nameStyle: computed('screenSizeService.width', function()
{
    this.get('screenSizeService.width');
    console.log('in computed');
    return this.getFontSize(2.5, 2, null, null, this.$())
}),

Then it runs correctly. The value of nameStyle has no direct relation to the screen width, but the container width which changes when the screen width changes.

This is why i read from the screen width.

Why would I need to get the value in order for it to work? Why wouldnt it just computed from when it changes and run that function?




get indirect child of an element by class name

I have a parent div element which I get like this...

this.$()

This returns the element correctly.

Now i want to select a grandchild element by class name. Here is the element structure.

enter image description here

So, at the moment I have the parent in a variable and I want to target the h2 element by class name 'profile-name'. So i do this...

this.$().find('.profile-name');

This does not return the element and I think its because its not a direct child. If i do this...

this.$().find('.profile-name-container');

It works and returns the container element.

How would I target the h2 by class name?




vendredi 26 avril 2019

Importing node module in ember-cli-build causing error in finding module `ember-resolver`

I'm trying to import an external dependency in my project by doing npm install --save-dev --registry=http://someDependency, and then use app.import('node_modules/someDependency') in ember-cli-build.js

But this is causing the following error:

Could not find module `ember-resolver` imported from `myapp/resolver`

All I have in myapp/resolver.js is:

import Resolver from 'ember-resolver';

export default Resolver;

Seems that it's looking for ember-resolver in myapp/resolver instead of node_module? But when I delete app.import('node_modules/someDependency') in ember-cli-build.js things are working fine.

Could someone give me some hint about what's going on here? Thanks a lot!


ember version: 2.18.2

node version: 9.0.0

pm version: 5.5.1




jeudi 25 avril 2019

Ember 3 computed property getter setter

With Ember v3.x, did something change with respect to setting a value for computed property ? In my class, I have a CP named "cp1"

Earlier with Ember 2.x, I used to do

this.cp1 = cp1

But with Ember 3.x, the above is not working. Do I need to update the way CP is set with Ember 3.x ?




How to modify an object hash in a template?

How to modify a hash/object value in a template?

eg.

foo-component.js
    settings: { color: "blue", size: 16, ...many others }
foo-template.hbs
    

my-route.hbs
    
        #! Change `settings.color` to "red" before passing to bar !#
        
    

eg. in a hash scenario

foo-template.hbs
    

my-route.hbs
    
        #! Change `settings.color` to "red" before passing to bar !#
        
    




Can I map/redirect routes to ports in the Ember FastBoot App Server?

I would like to map specific ports to certain routes on Ember FastBoot App Server so that I don't need a different url for different services.

Intended for production, I can not use development-only flags.

Example

  • www.example.com:443 Ember FastBoot App Server (4200)
  • www.example.com:443/api/* Node.js API (8080)
  • www.example.com:443/db/* CouchDB (5986)



Ember prepends application name in the script tag in production environment

I am trying to build my application in production environment, which seems fine. But as soon as I access the application, I get the following errors in the console:

Error parsing 'integrity' attribute. The specified hash algorithm must be one of 'sha256', 'sha384', or 'sha512'.

The hash seems fine, the problem is that the integrity attributes is like:

<script src="appname/path/assets/filename.js" integrity="appname/path/sha256...."></script>

instead of:

<script src="appname/path/assets/filename.js" integrity="sha256...."></script>

I don't really know why is it adding the name and the path in the first place, or where or how it's configured.

I also added the type attribute, that also got prepended with appname/path

Can anyone please help me with the correct configuration for this?




Emer js #LinkTo tag and its behaviour

I have an issue where, when i click a link from my page(LinkTo) , ctrl + click, it opens a new tab, but the controls go to the next tab in chrome, whereas in IE the control stay in the same page. I figured out that #linkTo behaviour in chrome is different. Can anyone help?

tried replacing with anchor tag but the routes dont work on single click




Ember: camelCase helper references not recognised

I upgraded Ember CLI from 2.4.6 to 2.8.0. After this, the helpers referred by camelCase names in the template are throwing the error Assertion Failed: A helper named "helperName" could not be found. If I change the references to helper-name from helperName, things work fine.




mercredi 24 avril 2019

TypeError: Cannot read property 'buildError' of undefined. What can it be?

Tried to "ember server" an application, but have got following error:

The Broccoli Plugin: [broccoli-persistent-filter:Babel > [Babel: inboxfront]: Babel: inboxfront] failed with:
TypeError: Cannot read property 'buildError' of undefined

Here are the details:

    at Scope.checkBlockScopedCollisions (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/scope/index.js:344:22)
    at Scope.registerBinding (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/scope/index.js:501:16)
    at Scope.registerDeclaration (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/scope/index.js:441:14)
    at Object.BlockScoped (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/scope/index.js:187:28)
    at Object.newFn (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/visitors.js:230:17)
    at NodePath._call (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/path/context.js:53:20)
    at NodePath.call (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/path/context.js:36:14)
    at NodePath.visit (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/path/context.js:88:12)
    at TraversalContext.visitQueue (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/context.js:118:16)
    at TraversalContext.visitMultiple (/home/username/inboxfrontend/node_modules/@babel/traverse/lib/context.js:85:17)

The broccoli plugin was instantiated at: 
    at Babel.Plugin (/home/username/inboxfrontend/node_modules/broccoli-plugin/index.js:7:31)
    at Babel.Filter [as constructor] (/home/username/inboxfrontend/node_modules/broccoli-persistent-filter/index.js:64:10)
    at new Babel (/home/username/inboxfrontend/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/index.js:37:10)
    at Class.transpileTree (/home/username/inboxfrontend/node_modules/ember-cli-babel/index.js:48:16)
    at Object.toTree (/home/username/inboxfrontend/node_modules/ember-cli-babel/index.js:58:30)
    at /home/username/inboxfrontend/node_modules/ember-cli-preprocess-registry/preprocessors.js:180:26
    at Array.forEach (<anonymous>)
    at processPlugins (/home/username/inboxfrontend/node_modules/ember-cli-preprocess-registry/preprocessors.js:178:11)
    at module.exports.preprocessJs (/home/username/inboxfrontend/node_modules/ember-cli-preprocess-registry/preprocessors.js:171:10)
    at EmberApp.appAndDependencies (/home/username/inboxfrontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1254:27)

Also

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: inboxfront -> ember-highcharts -> ember-getowner-polyfill -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: inboxfront -> ember-paper-stepper -> ember-cli-babel
Could not start watchman
Visit https://ember-cli.com/user-guide/#watchman for more info.
was unable to use: "events", fell back to: "polling"
Livereload server on http://localhost:7020

Don't you know what can it be?




mardi 23 avril 2019

how to render child component in ember.js v3.8?

Before Im working in v2.15 and i can render child component by



but cannot render child component on v3.8 how can i render child component?

<Component />




Ember.js - add record request has blank parameters

I am using ember-cli with a Rails API backend and am having some issues adding a new record.

I've set up the form and route and am able to retrieve the values from the form, but the save() does not pass these values back to the POST request for Rails, resulting in a blank record being created.

I would appreciate any assistance at all.

Adapter application.js:

import DS from 'ember-data';

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

Route:

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

export default Route.extend({
  model() {
    //return this.store.createRecord('book');
    return {};
  },

  actions: {
    saveBook(newBook) {
      var curr = this.store.createRecord('book', {
        title: newBook.title,
        author: newBook.author,
        genre: newBook.genre
      });
      alert("curr.title = " + curr.title);
      curr.save();
      this.transitionTo('books');
    },
  }
});

Template:

<h2>Add Book</h2>

<div class="layout-row">
   --}}
  <div class="form-horizontal">
    <div class="layout-row">
      <div class="layout-column flex-200">
      
      </div>
    </div>
    <div class="layout-row">
      <div class="layout-column flex-200">
      
      </div>
    </div>
    <div class="layout-row">
      <div class="layout-column flex-200">
      
      </div>
    </div>
    <div class="layout-row">
      <button type="submit" >Save</button>
    </div>
  </div>
</div>

Browser result using Ember Inspector:

{"data":{"id":"31","type":"books","attributes":{"title":null,"author":null,"genre":null}}}




Ember Data - Nested embedded records return null

We have a scenario when an embedded record of an embedded record returns null.

The relationship chain looks like this: userProfile --belongsTo--> organisation --hasOne (i.e. belongsTo)--> jurisdiction.

However, when fetching all userProfile records, the jurisdiction remains unpopulated.

So far, the respective serializers and models look like this:

UserProfile

Model

organisation: belongsTo('organisation', { async: false }),

Serializer

 attrs: {
    'organisation': { embedded: 'always' },
    ...
  },

Organisation

Model

userProfile: hasMany('userProfile', { async: false }),
jurisdiction: belongsTo('jurisdiction', { async: false }),

Serializer

  attrs: {
    ...
    'jurisdiction': { embedded: 'always' },
  },

Jurisdiction

Model

organisation: belongsTo('organisation', { async: false }),

Serializer

  attrs: {
    ...
    area: { key: 'jurisdictionArea' },
    name: { key: 'jurisdictionName' },
  },

I believe the issue might be that this part of the API doesn't appear to conform to the the JSON API spec, as an example userProfile response might look like:

...
organisation: {
   jurisdictionArea: "TAU"
   jurisdictionId: "82cfda0b-3180-41cf-b0fa-b1193655bc0b"
   organisationId: "960d4ec2-bc90-11e8-a355-529269fb1459"
}


I think this might be able to be resolved via the normalizeResponse or serializeBelongsTo methods in the organisation serializer, however, so far my attempts have not been successful. Any advice on how to resolve this would be much appeaciated.




How to register a service to trigger a method and override it

Need to register a service to trigger a method but override it in the class I'm working on

The service forces dirty objects to save with a custom function.

The class needs to use the service to activate the function.

Tried the following code:

operationManager:service()&

operationManager:service('operation-manager')

in init

this.register(this.get('operationManager'));

and override method in class

forcePendingSave: function(){console.log('need to get here')}

The service is not initting therefore not registering properly.




lundi 22 avril 2019

How to get rid of SourceMapConcat build error in emberjs?

I am always getting below error when I try to run ember server --proxy http://localhost:16000/ command. How do I solve this error? I have tried deleting tmp,build,bower_components & node_modules folder and tried with fresh workspace, but still facing the same issue. This is a dev environment, and this is working fine on production, but it is no longer working on my dev system.

Build Error (SourceMapConcat)

ENOENT: no such file or directory, open '/home/rick/Perforce/IIDIQ-UI/tmp/source_map_concat-input_base_path-aeXF7Gds.tmp/bower_components/blockUI/jquery.blockUI.js'

bower.json

{
  "name": "ui",
  "dependencies": {
    "bootstrap": "~3.3.6",
    "antiscroll": "git://github.com/Addepar/antiscroll#e0d1538cf4f3fd61c5bedd6168df86d651f125da",
    "jquery-mousewheel": "~3.1.4",
    "jquery-ui": "~1.11.4",
    "ember-bootstrap-table": "^0.1.2",
    "pace": "^1.0.2",
    "spin.js": "2.1.0",
    "datatables.net-bs": "^2.1.1",
    "socket-io-client": "^1.4.5",
    "highcharts": "^6.0.1",
    "seiyria-bootstrap-slider": "~6.0.6",
    "bootstrap-datepicker": "^1.7.1",
    "select2": "3.5.2",
    "d3": "^4.11.0",
    "pagination-pager": "3.2.0",
    "mousetrap": "^1.6.0",
    "components-font-awesome": "^4.6.3",
    "mark.js": "^8.9.0",
    "moment-timezone": "^0.5.14",
    "bootbox": "^4.4.0"
  },
  "resolutions": {
    "ember": "> 1.5.0-beta.3"
  }
}

package.json

{
  "name": "iidiq-ui",
  "version": "0.0.1",
  "description": "Small description for project goes here",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "devDependencies": {
    "bootstrap": "3.3.7",
    "bootstrap-datepicker": "^1.7.1",
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^2.4.1",
    "ember-bootstrap-datetimepicker": "^1.1.0",
    "ember-bootstrap-table": "1.0.0",
    "ember-changeset-validations": "1.2.6",
    "ember-cli": "^2.11.0",
    "ember-cli-app-version": "^2.0.0",
    "ember-cli-babel": "^5.1.7",
    "ember-cli-bootstrap-datepicker": "^0.5.6",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-htmlbars": "^1.1.1",
    "ember-cli-htmlbars-inline-precompile": "^0.3.6",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-is-package-missing": "1.0.0",
    "ember-cli-jshint": "^2.0.1",
    "ember-cli-moment-shim": "^3.1.0",
    "ember-cli-nouislider": "^0.13.0",
    "ember-cli-pace": "0.1.0",
    "ember-cli-qunit": "^3.0.1",
    "ember-cli-release": "^0.2.9",
    "ember-cli-sass": "6.1.1",
    "ember-cli-shims": "^1.0.2",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^1.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-cp-validations": "3.3.2",
    "ember-data": "^2.11.0",
    "ember-export-application-global": "^1.0.5",
    "ember-inline-svg": "0.1.7",
    "ember-link-action": "0.0.35",
    "ember-load-initializers": "^0.6.0",
    "ember-moment": "7.3.0",
    "ember-page-title": "^3.2.0",
    "ember-power-select": "^1.5.0-beta.0",
    "ember-radio-button": "1.1.1",
    "ember-resolver": "^2.0.3",
    "ember-select-2": "^1.3.0",
    "ember-source": "~2.11.0",
    "ember-table": "0.9.2",
    "ember-tether": "0.4.1",
    "ember-toastr": "1.6.2",
    "ember-tooltips": "2.9.0-beta.0",
    "ember-truth-helpers": "1.3.0",
    "ember-ui-blocker": "0.3.0",
    "ember-validations": "2.0.0-alpha.5",
    "ember-welcome-page": "^2.0.2",
    "eonasdan-bootstrap-datetimepicker": "^4.17.47",
    "handlebars-helpers": "0.8.2",
    "loader.js": "^4.0.10",
    "pagination-pager": "^3.1.0",
    "toastr": "^2.1.2"
  },
  "engines": {
    "node": "^4.5 || 6.* || >= 7.*"
  },
  "private": true,
  "dependencies": {
    "align-text": "^0.1.4",
    "arr-diff": "^4.0.0",
    "array-unique": "^0.3.2",
    "ember-cli-build-date": "^1.1.0",
    "ember-math-helpers": "^2.1.0",
    "handlebars-helpers": "^0.8.2",
    "is-ip": "^2.0.0"
  }
}

I am using the following

ember-cli: 2.18.2 node: 8.11.2 os: linux x64




yarn link doesn't run prepublish script, so what else can I do to develop an ember addon locally?

I have an addon that is linked to my app (for local dev) using yarn link

This creates a symlink in node modules to the addon directory.

However, I am using ember-cli-typescript, which has a prepublish script that builds my .ts files into .js, so when I am developing locally, prepublish doesn't get run, my .js do not get created, and the app crashes.

Maybe I could .gitignore all the .js and have them get built in ember-cli-build.js ?

Or should I be doing something besides yarn link for local dev?




Ancient non CLI ember project

I have a very outdated ember project and I have updated my codebase to use the latest version of jQuery, 3.4.0. The problem is, there is deprecated jQuery code in the ember app and it's causing errors. The one error I am seeing is "fixHooks". This has long been deprecated in jQuery. However, the ember app is pulling in

//cdnjs.cloudflare.com/ajax/libs/ember.js/1.7.0/ember.min.js (Yeah, ancient)

which uses fixHooks.

Do you know of a way or workaround I could do to get this to play nice with the newest version of jQuery?




dimanche 21 avril 2019

Correcting Invalid Route Naming

I'm currently working on a CRUD application - so far I've created an index route, a show route and and create route and have moved on to creating an update method. I've gone ahead and added a route, template and a controller, but whenever I try to click on a link to my new template I receive an error letting me know the following:

"This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid."

I'm linking to the update path through the show page and can confirm that the ID I'm passing into the link-to function exists. This being the case, I think that there's something likely wrong with my route name but can't figure out where I'm going wrong. I assume it's likely something wrong with the nested routes.

I've tried altering the order of my routes and have put console log statements in the controller I anticipated hitting once the link-to statement was hit - so far I haven't entered the controller.

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('about');
  this.route('contact');
  this.route('posts', function() {
    this.route('post');
    this.route('show', { path: '/:post_id' });
    this.route('edit', { path: '/:post_id/edit' })
    this.route('destroy', {path: ':post_id/destroy'});
  });
});

export default Router;


apps/routes/posts/edit.js

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

export default Route.extend({
    model(params) {
        console.log('hit this when edit route is hit')
        return this.store.findRecord('post', params.post_id);
      }
});

app/templates/post/show.hbs

<div class="jumbo show-posts">
 ...
</div>

   <div class="col-sm-offset-2 col-sm-10">
        <h3>Update post</h3>
   </div>





Load additional data into Model via Controller in Ember.js

I'm trying to load some additional data into the Model via the controller. I'm using RSVP.js for making an async api call to fetch some data. The issue that I'm currently running into is, the api is taking some time to get the response and as such what is getting added to the Model via the controller is a Promise. I wanted to get the data out of the promise and then pass it on to the template, so that it can be rendered in the screen.

fetch : function(params) {
  var getProfile = '/api/fetch',
  metric = params.metric,
  qsParts, getProfileUrl;

  qsParts = {metric: metric};
  getProfileUrl = Ember.prefixAPIServer(buildUrl(getProfile, {}, qsParts));

  let promise =  Ember.RSVP.hash({
    result: Ember.$.getJSON(getProfileUrl)
   });

  this.get('model').resultData = promise.then(result => {
             return result;
  })
} 

I tried other ways of doing the last part of setting the resultData, but it's not working. Can anyone help me with it ? Basically I want the data that is being fetched from the API call to be set to the Model. Or is there any way of getting the data out of the Promise in the template , which is using Handlebars.js ?




samedi 20 avril 2019

How to getting ajax promise by the head of response only?

To put it simply: I need to handle the response from rails API to make something, but I need the header of response only, without any of data.

But then is not getting the response when it contains the header only.

In details:

rails Controller action:

def index
  # some logic here ...
  head :created
end

ember component action:

let adapter = getOwner(this).lookup('adapter:application');
adapter.ajax(
  adapter.buildURL('/index'), 'POST', { some_param: 'some_content' }
).then(() => { 'do something here...' });

So in this implementation { 'do something here...' } is never used. But it works successfully if change the controller-action:

def index
  render json: [], status: :created
end

but I do not need to render some of json in response.

So, the question is:

how can run code 'do something here...' for controller-action:

def index
  head :created
end

Any help is appreciated.




vendredi 19 avril 2019

Is there a way to determine which component attribute updated?

Is there a way to determine which specific component attributes updated, without the component having to manually compare each attribute to its old value? I.e. I don't want my component to internally store the old objects of every attribute . I'm trying to avoid doing something like the following:

didReceiveAttrs() { 
     if( this.propA != this.oldPropA){
         // do something...
    }
     if( this.propB != this.oldPropB){
         // do something...
    }
}




I am attempting to upgrade from ember 1.7 to 1.13

I am trying to upgrade from an ancient version of ember (1.7) to the still ancient 1.13 and I am getting .js errors. I am not well versed with ember to begin with so all the help I can get will be appreciated.

I changed all instances of the code where it was using Ember.View.extend to Ember.Controller.extend

and since then, I am getting an error "Cannot read property 'noSignedUpAppts' of undefined".

Appt.Ember.js

function initEmberApp() {
    Ember.Handlebars.registerBoundHelper('stringFormat', function (g11nString, str) {
        return new Handlebars.SafeString(stringUtil.format(g11nString, str));
    });
    ApptApp = Ember.Application.create({
        rootElement: "#appointmentWrapper"
    });
    ApptApp.Router.map(function () {
        this.route("main", { path: '/' });
        this.route("mainParam", { path: "/:val" });
        this.route('mainId', { path: '/mainId/:appt_id' });
        this.route('mainDirect', { path: '/mainDirect/:appt_id' });
        this.route("schedule");
        this.resource('userSchedule', { path: '/schedule/:user_id' });
        this.route('scheduleId', { path: '/scheduleId/:appt_id' });
        this.route('userScheduleId', { path: '/userScheduleId/:ids' });
        this.route('scheduleSpecific');
        this.route('scheduleSpecificId',{path: '/scheduleSpecificId/:appt_id'});
        this.route('scheduleDate', { path: '/scheduleDate/:date' });
        this.route('scheduleResource', { path: '/scheduleResource/:resource_id' });
        this.route("settings");
        this.route("campus");
        this.route("noAccess");
    });
    ApptApp.history = {name:'',view:'',param:null, isSchedule:false}

    initViews();
}

function initViews() {
    initMain(ApptApp);
    initSchedule(ApptApp);
    initSettings(ApptApp);
    initCampus(ApptApp);
    initNoAccess(ApptApp);
}

ApptMain.js

function initMain(ApptApp) {

    ApptApp.MainController = Ember.Controller.extend({
        g11n: apptPortlet.g11n,
        ableToEdit: apptPortlet.ableToEdit,
        canManageSettings: apptPortlet.canManageSettings,
        canAdmin: apptPortlet.canAdmin,
        defaultDate: '',
        showMySchedule: false,
        apptId: '',
        isDirect: false
    });

    ApptApp.MainParamRoute = Ember.Route.extend({
        model: function (param) {
            var date = moment(param.val.replace(/-/g, '/'));
            return { defaultDate: (date.isValid() ? date.format('MM/DD/YYYY') : ''), showMySchedule: (param.val == 'myS') };
        },
        setupController: function (controller, model) {
            this.controllerFor('main').set('defaultDate', model.defaultDate).set('showMySchedule', model.showMySchedule).set('apptId', '').set('isDirect',false);
        },
        renderTemplate: function () {
            this.render('main');
        }
    });

    ApptApp.MainIdRoute = Ember.Route.extend({
        model: function (param) {
            var items = param.appt_id.split('|');
            var date = moment(items[1].replace(/-/g, '/'));
            return { apptId: items[0], defaultDate: (date.isValid() ? date.format('MM/DD/YYYY') : '') };
        },
        setupController: function (controller, model) {
            this.controllerFor('main').set('defaultDate', model.defaultDate).set('showMySchedule', false).set('apptId', model.apptId.toLowerCase()).set('isDirect', false);
        },
        renderTemplate: function () {
            this.render('main');
        }
    });
    ApptApp.MainDirectRoute = Ember.Route.extend({
        model: function (param) {
            var items = param.appt_id.split('|');
            var date = moment(items[1].replace(/-/g, '/'));
            return { apptId: items[0], defaultDate: (date.isValid() ? date.format('MM/DD/YYYY') : '') };
        },
        setupController: function (controller, model) {
            this.controllerFor('main').set('defaultDate', model.defaultDate).set('showMySchedule', apptPortlet.apptSetting != 0).set('apptId', model.apptId.toLowerCase()).set('isDirect', true);
        },
        renderTemplate: function () {
            this.render('main');
        }
    });

    ApptApp.MainView = Ember.Component.extend({
        didInsertElement: function() {
            var controller = this.get('controller');

            if (this.processRedirect(controller))
                return;

            this.renderView(controller);
        },
        renderView: function (controller, isRerender) {
            if (isRerender) {
                apptFullCal.destroy();
            }
            var g11n = controller.g11n;

            apptFullCal.init({
                data: {},
                defaultDate: controller.defaultDate,
                showMonth: true,
                showWeekNav: true,
                allowEditing: false,
                calElem: $("#myCalendar"),
                showWknd: apptPortlet.showWeekends,
                updateWknd: apptPortlet.updateSettings,
                g11n: controller.g11n,
                listViewPageSize: apptPortlet.listViewPageSize,
                noApptMesg: controller.g11n.noSignedUpAppts,
                rerender: function () {
                    apptFullCal.reload();
                    $("#myNotifications").apptNotification('render');
                },
                editEvent: function(appt, isClick, revertFunc, rerenderAction) {
                    var resource = {};
                    if (appt.resourceId != '' && appt.resourceEdit)
                        resource = apptPortlet.getResource(appt.resourceId);
                    $.apptDetails({ controller: controller, appointment: appt, g11n: controller.g11n, resource: resource, canAddAttendees: apptPortlet.canAddAttendees, rerender: function () { rerenderAction(); $("#myNotifications").apptNotification('render'); } });
                },
                readonlySources: function (viewName) { return viewName == 'month' ? [{ url: 'rpc/appointmentsinfo/getcalendaraggregate' }] : [{ url: 'api/calendarevents?fullCalendar=true&filter=conflictable' }]; },
                postApptRender: function (appt, elem, view) {
                    if (appt.isReadOnly) return;
                    var item = elem.find('.fc-content');
                    item.html(appt.isOwner ? appt.attendeeInfo : (appt.resourceId != '' ? appt.resourceName : appt.owner));
                    if (view.name != 'month') {
                        item.append($("<span class='fc-cus-event-info'>").html(appt.title));
                    }
                    if (appt.id == controller.apptId) {
                        controller.apptId = '';
                        apptFullCal.triggerClick(appt);
                    }
                    if (appt.newCommentCount > 0) {
                        var ctr = view.name == 'list' ? elem : item;
                        var comTxt = $("<span class='fc-comment'>").append($("<i class='fa fa-comment'/>")).append(view.name == 'list' ? stringUtil.format((appt.newCommentCount == 1 ? controller.g11n.newComment : controller.g11n.newComments), appt.newCommentCount) : '');
                        ctr.prepend(comTxt);
                    }
                },
                changeView: function(viewName) {
                    if (viewName == 'list')
                        $(".apptKeyInfo.otherEvents").hide();
                    else
                        $(".apptKeyInfo.otherEvents").show();
                    if (viewName == 'month')
                        $(".apptKeyInfo.otherEvents").removeClass("inactiveItem");
                    else
                        $(".apptKeyInfo.otherEvents").addClass("inactiveItem");

                    bindHelpText(g11n, viewName == 'list' ? '2' : (viewName == 'month' ? 0 : 1));
                }
            }, 'month');

            bindHelpText(g11n, 0);

            $("#myNotifications").apptNotification({
                g11n: apptPortlet.g11n,
                baseUrl: apptPortlet.baseUrl,
                renderFullTxt: true,
                callback: function(apptInfo) {
                    var date = moment(apptInfo.start);
                    if ((date.weekday() == 0 || date.weekday() == 6) && apptPortlet.showWeekends == false)
                        apptFullCal.showWeekends($("#myCalendar"), true, date);
                    controller.set('apptId', apptInfo.id);
                    apptFullCal.gotToDate('agendaDay', date);
                }
            });

            $("#peopleChooser").peopleChooser({
                peopleSource: 'rpc/appointmentsInfo/GetUserSearch',
                watermark: controller.g11n.watermark,
                onSelect: function(person) {
                    if (person.isResource)
                        controller.transitionTo('scheduleResource', person.id);
                    else
                        controller.transitionTo('userSchedule', { id: person.id, imgUrl: person.imgUrl, name: { full: person.fullName } });
                }
            });

            if (controller.canManageSettings || controller.canAdmin)
                $(".permissionAction").click(function() { ApptApp.history = { name: '', view: 'main', isSchedule: false }; });

            var schLinkAction = this.bindScheduleLink;
            $(".permHosts").hide();
            if (apptPortlet.canManageSettings && (apptPortlet.apptSetting == 2 || (apptPortlet.apptSetting == 3 && apptPortlet.resourceId.length > 0))) {
                var resource = apptPortlet.apptSetting == 2 ? null : apptPortlet.getResource(apptPortlet.resourceId);
                if (apptPortlet.apptSetting == 2 || (resource != null && resource.canEdit)) {
                    $(".permHosts").show().find('a').html("<i class='fa fa-group'></i>" + (apptPortlet.apptSetting == 2 ? g11n.apptHosts : g11n.managersAndHosts))
                        .unbind('click').click(function(e) {
                            e.preventDefault();
                            $.apptManageHosts({
                                g11n: controller.g11n,
                                resource: resource,
                                isResource: resource != null,
                                portletId: apptPortlet.portletId,
                                onSave: function(res) {
                                    if (apptPortlet.apptSetting == 2) {
                                        apptPortlet.hosts = res;
                                        schLinkAction(controller);
                                    } else {
                                        apptPortlet.hosts = res.hosts;
                                    }
                                }});
                        });
                }
            }


            if (controller.showMySchedule) {
                $(".mySchedule").hide();
                this.bindResourceInfo(controller);
            } else {
                $(".mySchedule").show();
            }
            this.bindSidebar(controller);
        },
        bindSidebar: function(controller) {
            var campus = $(".campusWrapper").hide();
            var myfac = $(".myFacWrapper").hide();
            $.get('rpc/appointmentsinfo/getsidebarinfo/', function (sidebarInfo) {
                if (sidebarInfo == null) return;
                if (sidebarInfo.campusResources != null) {
                    var ul = campus.find('#campusResources').empty();
                    for (var key in sidebarInfo.campusResources) {
                        ul.append($("<li>").append($("<a href='#'  class='activeItem apptStrong'>").data('id', key).html(sidebarInfo.campusResources[key]).click(function (e) { e.preventDefault(); controller.transitionTo('scheduleResource', $(this).data('id')); })));
                    }
                    if (ul.find('li').length > 0)
                        campus.show();
                }
                if (sidebarInfo.currentFaculty != null && sidebarInfo.currentFaculty.length > 0) {
                    myfac.show();
                    var container = myfac.find(".myFacUsers").empty();
                    $.each(sidebarInfo.currentFaculty, function (i, fac) {
                        var div = $("<div class='myFac'>");
                        div.append($("<a class='activeItem apptStrong'>").html(fac.name).click(function (e) { e.preventDefault(); controller.transitionTo('userSchedule', { id: fac.id, imgUrl: fac.imgUrl, name: { full: fac.name } }); }));
                        if (!fac.hasAvailAppts)
                            div.append($("<span class='pc-details'>").html(controller.g11n.noAppt));
                        $.each(fac.sections, function (j, sec) {
                            div.append($("<div class='inactiveItem itemInfo'>").html(sec));
                        });
                        container.append(div);
                    });
                }
            });
        },
        processRedirect: function (controller) {
            if (apptPortlet.name == null) {
                controller.transitionTo("noAccess");
                return true;
            }
            if (controller.isDirect) return false;

            var date = controller.defaultDate != null && controller.defaultDate != '' ? moment(controller.defaultDate).format('MM-DD-YYYY') : null;
            if ((apptPortlet.resourceId != '' || apptPortlet.apptSetting == 2) && !controller.showMySchedule) {
                var url = apptPortlet.apptSetting == 2 ? 'scheduleSpecific' : 'schedule';
                if (controller.apptId != '' || date != null) {
                    controller.transitionTo(url + "Id", (controller.apptId + '|' + date));
                }
                else
                    controller.transitionTo(url);
                return true;
            }
            else if (apptPortlet.apptSetting == 1 && !controller.showMySchedule && apptPortlet.hosts != null && apptPortlet.hosts.length > 0) {
                var host = apptPortlet.hosts[0];
                if (controller.apptId != '' || date != null) {
                    controller.transitionTo('userScheduleId', host.id + '_' + ((controller.apptId == '' ? ' ' : controller.apptId) + '|' + date));
                }
                else
                    controller.transitionTo('userSchedule', { id: host.id, imgUrl: host.imgUrl, name: { full: host.name } });
                return true;
            }

            return false;
        },
        bindScheduleLink: function (controller) {
            var showLink = false;
            if (apptPortlet.resourceId != '') {
                var resource = apptPortlet.getResource(apptPortlet.resourceId);
                $(".scheduleLink").html(stringUtil.format(controller.g11n.bckToSchedule, resource.name)).unbind('click').click(function (e) { e.preventDefault(); controller.transitionTo('schedule'); });
                showLink = true;
            }
            else if (apptPortlet.apptSetting == 1) {
                var host = apptPortlet.hosts[0];
                $(".scheduleLink").html(stringUtil.format(controller.g11n.bckToSchedule, host.name)).unbind('click').click(function (e) { e.preventDefault(); controller.transitionTo('userSchedule', { id: host.id, imgUrl: host.imgUrl, name: { full: host.name } }); });
                showLink = true;
            }
            else if (apptPortlet.apptSetting == 2) {
                var names = '';
                var userCount = apptPortlet.hosts.length;
                for (var i = 0; i < userCount; i++) {
                    names += " " + apptPortlet.hosts[i].name;
                    if (userCount > 1 && (userCount - i != 1)) {
                        names += userCount - i == 2 ? ", " + controller.g11n.and : ",";
                    }
                }
                $(".scheduleLink").html(stringUtil.format(controller.g11n.bckToSchedule, names)).unbind('click').click(function (e) { e.preventDefault(); controller.transitionTo('scheduleSpecific'); });
                showLink = true;
            }
            if(showLink)
                $(".bckToSchedule").show();
            else
                $(".bckToSchedule").hide();
        },
        bindResourceInfo: function (controller) {
            this.bindScheduleLink(controller);

            var ul = $("#userSchedules").empty();
            if (apptPortlet.ableToEdit) {
                ul.append($("<li>").append($("<a href='#' class='activeItem apptStrong'>").html(apptPortlet.name.full).click(function (e) { e.preventDefault(); controller.transitionTo('userSchedule', apptPortlet.id); })));
                $(".rg-sidebar").show();
            }
            $.get('rpc/appointmentsInfo/GetMySchedules/', function (schedules) {
                if (schedules == null) return;
                for (var key in schedules) {
                    ul.append($("<li>").append($("<a href='#'  class='activeItem apptStrong'>").data('id',key).html(schedules[key]).click(function (e) { e.preventDefault(); controller.transitionTo('scheduleResource', $(this).data('id')); })));
                }
                if (schedules.length > 0)
                    $(".rg-sidebar").show();
            });
        }
    });
    function bindHelpText(g11n, screen) {
        $(".apptHelpWrapper").appointmentHelp({ g11n: g11n, isHost: apptPortlet.ableToEdit, portletId:apptPortlet.portletId, screen: screen });
    }
}




EmberJs deprecate component lifecycle hook didReceiveAttrs

For the Ember version 2.16,they have removed the arguments passed to the, didReceiveAttrs component lifecycle hooks. Now previously I was getting arguments in the form of object.

newAttrs:

EmptyObject: 
{
  dataTestId: "test-object"
  items: MutableCell {__MUTABLE_CELL__       [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: Array(27)}
  prompt: SafeString {string: "Select an Initiator Group"}
  required: true
  selected: MutableCell {__MUTABLE_CELL__ [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: undefined}
  __proto__: Object
}

After deprecation how to get such object in the didReceiveAttrs?




jeudi 18 avril 2019

What is the proper ember.js-way to react to a changing checkbox

I have a checkbox like this:



When I click the checkbox the property is changed. Now I like to call a function to persist the property. But what is the best way to do this?

  1. I could bind an observer to property, but this is consindered bad.
  2. I could bind an action to input oder click.

    
    
    

    This doesn't work because the property has still the old value when the action is called.

  3. Extending the class Checkbox:

    import Checkbox from '@ember/component/checkbox';
    Checkbox.reopen({
        onChange: null,
        change() {
            this._super();
            if (this.onChange) this.onChange();
        }
    });
    ...
    
    
    

    But the function change is not documented, even though the source code indicates that it is feasable to override.

  4. I could bind an action to didUpdate or didUpdateAttrs, but the action is called twice. In my case this wouldn't be a problem, because the property is part of a model, so I could call model.get('hasDirtyAttributes') in the action. [Update] In my test case the action was called twice but in my real code it is only called once, so this seems to be the best solution?[/Update]

So what is the proper ember.js-way to do this?




mercredi 17 avril 2019

Ember js CLI addon using Foundation CSS complains about missing plugin

I am using an ember cli addon in another ember cli app. The addon uses Foundation CSS and when I try to run the app it complains: Error: no mixin named foundation-flex-video

This addon is used in other Ember cli apps and it does not throw this error on those apps. I have been installing/removing NPM packages in the hope of remedying this but I can't find out why the app is complaining about this mixin. It does not even use the classes that it is complaining about.




how to call an element in another layer hbs

There two hbs files, one is under another layer, for example, at testA.hbs, it has,

<div>
      
</div> 
<div id="area">
     Hello, world 
</div>

At testB.js, I want to call the id "area" at testA.hbs. How can I achieve this? Thank you.




Reinstall node using nvm on OS X without removing node_modules?

Following the latest advice I decided to remove a previous working Homebrew node install and use nvm to install node instead, and also set things up to avoid using sudo.

However, before going further

I carefully cleaned out the following folder (owned by my user) except for two modules used for a long-standing Ember project that uses an older version of node (because I'm not confident of reinstalling the required version of them later):

/usr/local/lib/node_modules/
  bower
  ember-cli

If I keep the existing /usr/local/lib/node_modules/ folder with the versions of bower and ember-cli, will this cause any issue on installing nvm and then the node versions I need?




Is there any library which support emberjs-1.6 for integrate Firebase

I am trying to use Firebase services for my existing emberjs-1.6 application. For that is there any library exist or Is there any alternative method to use the javascript library for this integration?

I've tried to use javascript library to do this (https://www.gstatic.com/firebasejs/5.9.4/firebase.js)

    var config = {
        apiKey: "---",
        authDomain: "---",
        databaseURL: "---",
        projectId: "---",
        storageBucket: "---",
        messagingSenderId: "---"
    };

    firebase.initializeApp(config);
    db=firebase.firestore();

    db.settings({timestampsInSnapshots:true});

    db.collection('cafes').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            console.log(doc);
        });;
    })

I expected to display data in my Firestore on the web browser console. but it produces the following error message

"Uncaught FirebaseError: Invalid collection reference. Collection references must have an odd number of segments, but has 0 "




mardi 16 avril 2019

How to use imported third-party js (not addon/npm package) in controller/component?

I have put my js files (eva.min.js/feather.min.js and so on) in vendor dir, then I imported them in ember-cli-build.js (app.import('vendor/eva.min.js')). But how to use it?

I tried something like import eva from 'eva'/'eva.min'/'eva.min.js' or import Eva from 'eva'; and so on, but it doesn't work.

  app.import('vendor/eva.min.js');
  app.import('vendor/bootstrap.min.js');
  app.import('vendor/feather.min.js');
  app.import('vendor/popper.min.js');
  app.import('vendor/jquery-slim.min.js');
  app.import('vendor/swipe.js');

import Swipe from 'swipe';

Console usually gives me the 'could not find the module' mistake. And I don't have deep background in programming, so I would high appreciate if you explained the problem as simple as possible.




Dynamically added assets prefix in the image URL - Ember-CLI

I am trying to load the app by using ember serve.some of the images or not found error getting. In CSS : background-image: url(assets/images/image.svg); its redirected to http://localhost:4200/assets/assets/images/image.svg 404 (Not Found) bcz in this url two assests name added.

when add '/' in the prefix of url am able to see the image in the app. background-image: url(/assets/images/image.svg); its redirected to http://localhost:4200/assets/images/image.svg

Kindly help anyone pls...




lundi 15 avril 2019

dynamic looping on a controller property

I am using ember 2.17.

I added this property to a controller :

export default Controller.extend({
  newAttachments: new Array()
...

I add elements in it through this controller action :

setAttachment(file){
      console.log('trying')
      this.get('newAttachments').push(file)
    }

When I us the action, the message is displayed in the console, and in Ember inspector I can see the array is no longer empty :

enter image description here

However, the following code in the view has no output :


  <p>in loop</p>


Why is it not displaying anything? In a component it would work, why not here ?




What is the recommended way to make a PUT request to an external API in EmberJS?

I have a simple app that retrieves a record from an external API and displays the value ("day"). The day value can be incremented by passing it into a component with a simple action. My app is retrieving the record correctly and is successfully passing it to the component. But once it has incremented the value I can't figure out the best way to save the record back to the external API.

My route fetches the object like this:

export default Route.extend({
  model() {
    return this.get('store').findRecord('world', '5cb0f8bd3b74cf22b75e1a37', { reload: true });
  },
})

This is my model:

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

const { attr } = DS;

export default Model.extend({
  day: attr('Number'),
});

Here is my component:

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

export default Component.extend({
  router: service(),
  store: Ember.inject.service(),
  actions:{
    incrementHour() {
    this.day++;
    }
  }
});

Once this value has been incremented, what is the recommended way to push this back to the API?




Ghost URL loaded in Ember

I have a weird behaviour. We are working with Ember on Git for a while now, but in this new project, I'm having for the first time an issue following the bellow steps:

  1. Add a new .svg image and delete the old .png
  2. Then I change all references to the .png with the .svg image name
  3. Check that is working. It does
  4. git add .
  5. git commit -m "my message"
  6. git pull [branch]
  7. git push [branch]
  8. Go back to the browser and images are broken
  9. Look at the generated code and src url is pointing to the old .png image

We find

<img class="logo" src="./assets/images/logo.png" alt="logo">

instead of:

<img class="logo" src="./assets/images/logo.svg" alt="logo">

  1. Ask my partner to get my code in the branch and check if he's getting the same issue. He doesn't, he sees the new .svg image.

  2. I deleted the local branch and bring it back again. The issue is gone.

  3. I do some changes and pull again and then the issue comes back.

I have the following code in the template.hbs

<img class="logo" src="" alt="logo">

and this in the component:

logo: computed('logo', function() {
        return htmlSafe('./assets/images/' + ((config.APP.logo) ? config.APP.logo : 'logo.svg'));
    })

This is calling to an environment condition that determines the logo that have to be loaded.

Did this happened to any of you? Do you have any idea of how to prevent this happen?




Ember & Typescript - defining actions

I am trying to create my first ember app with typescript and I have trouble with how actions are defined. According to several tutorials I found, I should use decorator @action like this:

import { action } from '@ember-decorators/object';

@action sayHello(){
}

But I am getting error:

Module '"../../../node_modules/@ember-decorators/object"' has no exported member 'action'.

In my package.json I have defined:

"ember-decorators": "^6.0.0",

What am I doing wrong?

Thanks




dimanche 14 avril 2019

How to iterate a JSON payload in ember-infinity?

I'm getting the data using API request from "http://example.com/people.json". The response data will be like following code.

{ 
 people: [
   { 
     name: 'Andrew Thomson',
     age: 32
   },
   { 
     name: 'Callum Falconer',
     age: 28
   },
   { 
     name: 'Evelia',
     age: 26
   }
 ],
 'meta': {
   'total': 20,
   'total_pages': 2,
   'page': 1
  }
}

I need to iterate this response using ember-infinity. How do I make this work with ember-infinity?




How to update specific property on array of object?

Say "I initialized an array with predefined values like this" in my controller

  data: A([
    {
      lat: 14.5619175,
      lng: 121.0197196,
      title: "Jazz Mall",
      open: false
    },
    {
      lat: 14.5660656,
      lng: 121.0295681,
      title: "Avalue Residences",
      open: false
    },
    {
      lat: 14.5661493,
      lng: 121.0282417,
      title: "Century City",
      open: false
    }
  ])

Now, How can I update values to something like

title: "Jazz Mall" to title: "Value has been change"




vendredi 12 avril 2019

How to display API response in Ember template?

I'm using Ember to retrieve a specific record from a REST API and display it on a template. I can console log the payload from my serializer and it displays the object correctly, but my template can't seem to access it.

The payload has the following structure:

{ 
  _id: 5cb0f8bd3b74cf22b75e1a37,
  name: 'Mu',
  hour: 0,
  day: 0,
  week: 0,
  month: 0,
  year: 753,
  size: 1,
  detail: 1,
  createdAt: 2019-04-12T20:44:45.691Z,
  updatedAt: 2019-04-12T20:44:45.691Z,
  __v: 0 
}

My ember route looks like this:

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

export default Route.extend({
  model() {
    this.get('store').find('world', '5cb0f8bd3b74cf22b75e1a37');
  },
})

My adapter looks like this:

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host: 'http://localhost:3000',
  pastForType(){
    return 'worlds';
  },
});

Here is my ember model for worlds:

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

const { attr } = DS;

export default Model.extend({
  name: attr('String'),
  hour: attr('Number'),
  day: attr('Number'),
  week: attr('Number'),
  month: attr('Number'),
  year: attr('Number'),
  size: attr('Number'),
  detail: attr('Number')
});

The payload is normalized by my serializer:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  primaryKey: '_id',

  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    payload = { worlds: payload };
    console.log(payload);
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

When the route is called the console outputs this:

Object { worlds: {…} }

The data is correct inside the object, but when I try to access in my handlebars template nothing is displayed.

Am I failing to pass the object to the template somehow? Am I just referring to it incorrectly?




Ember invoking closure action

In Ember JS, say I have a component defined as below (HBS/JS)

//parent.hbs


// app/components/longclaw-sword.js
export default Ember.Component.extend({
  click() {
    this.attack();
  }
});

Is there any difference between calling the closure action using this.attack() V/s this.attr.attack() ?

In which cases is "attr" used ? Can it be used for reference to normal properties OR is it only for actions ?




jeudi 11 avril 2019

Ember-engines as peerDependency

I am a bit confused with the peerDependency concept from an Ember engines perspective.

What does “peerDependency” signify when using Ember engines ? Should only the parent/host app provide the peerDependency as “ember-engines” ? What would happen if both the child & host app specifies this as peerDependency with a different version ?




Why it taking too long to resolve getUserMedia in Firefox, even after stopping all MediaStreamTrack?

I have a drop-down to select different media devices for recording audio and video.

While changing the device in Firefox, I'm stopping all the active mediaStreamTrack then again catching the stream with the selected device. But its taking too much time to resolved. Its working fine in Google Chrome.

_clearStream() {
    if(this.get('mediaStream')) {
      this.get('mediaStream').getAudioTracks().forEach(track => track.stop())
      this.get('mediaStream').getVideoTracks().forEach(track => track.stop())
    }
    if(this.get('audio.mediaStream')) {
      this.get('audio.mediaStream').getAudioTracks().forEach(track => track.stop())
      this.get('audio.mediaStream').getVideoTracks().forEach(track => track.stop())
    }
    this._getStream()
  },

  _getStream() {
    const constraints = {
      audio: { deviceId: this.get('audioSourceDevice') ? { exact: this.get('audioSourceDevice.deviceId')} : undefined },
      video: { width: 320, height: 240, deviceId: this.get('videoSourceDevice') ? { exact: this.get('videoSourceDevice.deviceId')} : undefined }
    }
    return navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
      this.set('mediaStream', stream)
      this.set('audio.mediaStream', stream)
      return stream
    })
  }




mercredi 10 avril 2019

Integrate SASS/SCSS on Ember Project with POD structure

I just want to ask what is the best approach to integrate sass/scss on ember project?

Currently my project is in pod structure and I just import style.scss on main app.scss under styles folder. Is it fine or there is a better approach?

--- app
---- pods
------- home
---------- template.hbs
---------- controller.js
---------- style.scss
---- styles
------- app.scss

Cheers,




can multiSelect be Possible with Ember Power-select?

I have tried everything for Power-select in ember. But I'm not able to implement multi-select with power-select. I need to select multiple options of a single group.

Is it Possible?




Extending window in ember.js

How can I inject something that would be accessible in window.something

before dependencies would be loaded? I tried to do it in .ember-cli-build, but I don't know how to get access here to window

I want to do alias from another library

window.something = anotherLibrary

for now it could be even window.something = "something"

the most important thing to do it before other dependencies (because they waited for it and it doesn't exist)




mardi 9 avril 2019

Ember init failing to recognize _super

So my app has this component.js:

import Component from '@ember/component';
import layout from './template';
export default class MyComponent extends Component {
    layout = layout;

    init() {
        this._super(...arguments);
    }
}

When the component is rendered I am getting this error in the chrome console:

Assertion Failed: You must call `this._super(...arguments);` when overriding `init` on a framework object. Please update <savings-toolkit@component:my-component::ember2445> to call `this._super(...arguments);` from `init`.

The content is not loaded. I wish I could say more, but seriously, what the heck?

Yes, it was initially more much content when I started. It is, however, at this time, literally nothing more than the above.




jeudi 4 avril 2019

Models in ember-fastboot loaded twice

An ember-cli app loads a random model on a certain page. This works as expected.

Now that I enabled ember-fastboot server-side rendering, the model is loaded client-side.

Upon rehydration, ember.js loads a random model again, client-side. This causes the page upon opening to show one model for part of a second (depending on internet speed), and then it changes.

I am guessing that the model needs to be loaded client-side for all client-side functionality that needs the model to be loaded.

Is it possible to prevent fetching a new random model on first pageview right after fastboot? How do I prevent a model from being reloaded client-side?




Ember.js record.save() is successful, but object has state inflight

I am using a fairly new version of Ember (Ember 3.7.2, Ember Data: 3.7.0)

I create an object in the client and I create a GUID as the ID. I save it to the backend with record.save() and I use the Json Api Adapter. The backend changes the ID to an integer (An autoincrement in the database) and the payload returned from the server includes the newly saved object with this new ID. This ID is not used to anything. The object in the client keeps it GUID and it now has the state "isSaving"=true. So, if I later try to delete this object I get this error:

Attempted to handle event deleteRecord on while in state root.loaded.created.inFlight.

I am using a standard version of the JSONAPISerializer. I have subclassed the JSONAPIAdapter to include this mehtod:

generateIdForRecord: function(/* store, record */) {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random()*16)%16 | 0;
    d = Math.floor(d/16);
    return (c==='x' ? r : (r&0x3|0x8)).toString(16);
  });
  return uuid;
}

What should I do to save properly and don't get an error when I try to delete the object?




Integration tests CRUD Ember.js

I need to do integration tests for my Ember app, for example in the user template :

<div class="container">

<h1> </h1>
<p>Age:  years old</p>
<p>Job: </p>
<img src="" alt="img" id="image">


</div>

I have to test that the list of users is correctly displayed. Is it possible to do so ?

I have never done that and I'm kind of lost here. Would it be something like :

test('it renders all users', function(assert) {
this.set('users', [
{ firstName: 'Tubby'},
{ firstName: 'Spot'},
{ firstName: 'Chester'},
{ firstName: 'Frisky'}
]);

 this.render(hbs``);
 assert.equal(this.$('.user').length, 4);
 });

Even though I read many articles about the integration tests, I still don't understand if it can be used for something that is not a component.

What about redirection ? Let's just say that I have to write an integration test that verifies that the redirection is okay. Can I do that with integration tests ?

Thanks for your help.




mercredi 3 avril 2019

How to mount routable ember engine to my consuming app?

i try to mount an engine to my project as per the demo:

consuming app: https://github.com/dgeb/ember-engines-demo

engine app: https://github.com/dgeb/ember-blog-engine

the demo works well. But when i mount the ember-blog-engine to my own consuming app, error occurs and the error message is "Error: Could not find module ember-blog-engine/engine imported from (require)".

how i add the engine:

  1. package.json
"dependencies": {
  "ember-engines": "0.6.3",
  "ember-blog-engine": "path-to/ember-blog-engine",
   ...
},

  1. router.js
this.mount('ember-blog-engine', {as: 'blog'});

  1. I also add active-session.js and blog-data.js in services folder because those service is used by the demo engine.

I found the ember-blog-engine's source code is never built into vendor.js, when exec ember build, the console shows the engine is in dead module. ember build console is list as below:

...
addon-tree-output/modules/ember-blog-engine/components/date-picker.js
addon-tree-output/modules/ember-blog-engine/config/environment.js
addon-tree-output/modules/ember-blog-engine/engine.js
addon-tree-output/modules/ember-blog-engine/initializers/hello.js
addon-tree-output/modules/ember-blog-engine/instance-initializers/hello-instance.js
addon-tree-output/modules/ember-blog-engine/routes.js
addon-tree-output/modules/ember-blog-engine/routes/application.js
addon-tree-output/modules/ember-blog-engine/routes/index.js
addon-tree-output/modules/ember-blog-engine/routes/new.js
addon-tree-output/modules/ember-blog-engine/routes/post.js
addon-tree-output/modules/ember-blog-engine/routes/post/comments.js
addon-tree-output/modules/ember-blog-engine/templates/application.js
addon-tree-output/modules/ember-blog-engine/templates/components/date-picker.js
addon-tree-output/modules/ember-blog-engine/templates/index.js
addon-tree-output/modules/ember-blog-engine/templates/new.js
addon-tree-output/modules/ember-blog-engine/templates/post.js
addon-tree-output/modules/ember-blog-engine/templates/post/comments.js
addon-tree-output/modules/ember-blog-engine/templates/post/index.js
...
dead 239
traversed 1347




How to change checked radio button default in ember?

hay I have a code for the radio button, the default checked code shows allbrand and I want to change the default checked to ncarbrand

this code component.hbs:

 
     <div class="">
         <div class="form-group">
             <label>Kondisi</label>
             <div class="input-group">
                 <div class="btn-group" data-toggle="buttons">
                     <label class="btn btn-orange active"  style="margin-bottom:0px;">
                         <input type="radio" name="condition" autocomplete="off" value="ncar">
                          Baru
                          Baru 
                     </label>
                     <label class="btn btn-orange active"  style="margin-bottom:0px;">
                         <input type="radio" name="condition" autocomplete="off" value="ucar">
                          Bekas
                          Bekas 
                     </label>
                 </div>
             </div>
         </div>
     </div>


this code component.js:

  _filters: computed('filters', 'cart.contents.condition', function() {
      let obj_brands_all = [],
          obj_brands_new = [],
          brands = get(this, 'filters.brand').split('|'),
          ncarBrands = ['HONDA', 'SUZUKI', 'DAIHATSU', 'WULING', 'TOYOTA']

      for (let brand of brands) {
          if (this.get('cart.contents.condition') === 'ncar' && ncarBrands.includes(brand)) {
              obj_brands_new.push({ 'index': brand, 'value': brand, 'id': brand.dasherize() });
          } else {
              obj_brands_all.push({ 'index': brand, 'value': brand, 'id': brand.dasherize() });
          }
      }
    return {
        brands: (this.get('cart.contents.condition') === 'ncar')obj_brands_new.sortBy('value') : obj_brands_all.sortBy('value')
    }
})

this code template.hbs:

<ProductFilterNew @filters= @origin="new" @targetUrl="new" @carmodels= @isNcar=true @isNewPage=true />

I expect the output list brand ['HONDA', 'SUZUKI', 'DAIHATSU', 'WULING', 'TOYOTA']




Ember build adds read permission to some files but not others

In my Ember.js project, I have the following files:

public/img/pixels.png 0640
public/img/vector.svg 0640

After doing ember build -prod in a Docker container, I have the following files:

img/pixels-d72816e93259890d380ddf05acb748e7.png 0644
img/vector.svg 0640

Notice how the hashed file changed from 0640 to 0644.

Now on this Ember app, all references to pixels.png work fine, but references to vector.svg result in unavailable images.

What causes Ember to add the read bit for some, but not others? How can I force this to happen to all files from public? Shouldn't Ember do this automatically? (e.g. is this a bug?)