vendredi 31 mars 2017

Developing basic version of linkedin social media website using ember.js

It should have CRUD(Create,Read,Update,Delete) functionality and couchDB for maintaining sessions.Any help will be appreciated.




Error while trying to self reference a model in ember.js

I'm trying to create a self-referenced property in a model, but I'm getting the following error:

Error while processing route: index No model was found for 'menu' Error

Here is my model (menus.js):

import DS from 'ember-data';

export default DS.Model.extend({    
  title: DS.attr('string'),
  link: DS.attr('string'),
  isActive: DS.attr('boolean'),
  children: DS.hasMany('menus', { inverse: null }),
});

I'm trying to returning a list from a Web API. Here is my API JSON return:

[
  {
    "id": 1,
    "title": "Test",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 4,
        "title": "Test 2",
        "link": "index",
        "isActive": false
      }
    ]
  },
  {
    "id": 2,
    "title": "Test 2",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 5,
        "title": "Test 4 ",
        "link": "index",
        "isActive": false
      }
    ]
  },
  {
    "id": 3,
    "title": "Test 5",
    "link": "index",
    "isActive": false,
    "children": [
      {
        "id": 6,
        "title": "Test 6",
        "link": "index",
        "isActive": false
      },
      {
        "id": 7,
        "title": "Test 7",
        "link": "index",
        "isActive": false
      }
    ]
  }
]




How to work with couchdb in integration with ember.js?

I am developing an application which requires connection of ember.js with couchdb and need to know how it's done asap.




Firebase + Ember 2.0: The Torii adapter must implement `open` for a session to be opened

I'm having an issue with facebook authentication with the torii adapter, the error being: 'The Torii adapter must implement open for a session to be opened'.

I've visited many tutorials, and tried all presented methods, but most of them are usually old ember code and none of them seem to actually work.

Current state: I am able to login, I get the facebook popup and I can authorize. Proof of this would be a route that I set to authenticatedRoute, that effectively disables after logging in. Strangely enough, however, my doesn't trigger.

Using fiddler, I can also see the response from the API containing a JSON response with all credentials from the user I authenticated with. In the firebase console, I can see the authorized user, reset its password, deny access,...

All this leads me to believe that it's 'merely' a front-end issue where I can't seem to establish a proper 'session' to work with.

My end goal would be to pick up the relevant user data and transfer it to my firebase backend as a 'user' entry, allowing for quick registration for site visitors, but I'll be more than glad to have an active session so I can work out the rest on my own.

As a front-end rookie (I normally code C#), Ember may not have been the best choice to get the hang it, but I'm this far now, I'm not about to let it all slide and pick up a different framework.

My code:

config/environment.js

firebase: {
    apiKey: 'xxxxxxx',
    authDomain: 'myappname.firebaseapp.com',
    databaseURL: 'http://ift.tt/1sg9T8I',
    storageBucket: 'myappname.appspot.com',
    messagingSenderId: '1234567890'
  },

    torii: {
      sessionServiceName: 'session'
    }

torii-adapters/application.js (I've changed this so much, I can't even remember what the original code was, because none of what I change/add/delete here seems to do anything at all.)

export default Ember.Object.extend({
  store: Ember.inject.service(),

  open: function(authorization) {
    var firstName = authorization.firstName,
    store = this.get('store');
    return store.find('user', firstName).then(function(user) {
      return {
        currentUser : user
      };
    });
  }
});

routes/application.js

import Ember from 'ember';

    export default Ember.Route.extend({
      beforeModel: function() {
        return this.get('session').fetch().catch(function() {
        });
      },

      actions: {
             login: function(provider) {
                 this.get('session').open('firebase', {
                      provider: provider,
                 }).then.transitionTo('about');
             },

             logout: function() {
                 this.get('session').close();
             }
         }
    });

login.hbs

<div class="jumbotron text-center">
  <a  class="btn"></a>
</div>


    <span>Currently logged in as  with
     - <a >Sign out</a></span>





Bootstrap - changing the width of a form

I have the following code in an ember application for a .hbs template file (basically it's just a chat box for a user to enter text, with "Back" and "Send" buttons either side):

<div class="row">
<div class="chat-form text-left">
<button class="btn btn-default" >Back</button>
<form class="form-inline" >
<div class="form-group">
<label class="sr-only">Chat Message</label>

</div>
<button type="submit" class="btn btn-default">Send</button>
</form>
</div>
</div>

Currently the text box is too narrow and I want to make it a few times wider, I'm aware of columns and spans in bootstrap but as a complete beginner I'm not sure how to do it properly in this case.




Ember link-to not working when not passed a model

I have a template at the level just below the application route in my Ember application which contains a navbar with three tabs that should go to three sub routes. The link tos are set up like so:

Route name

If you right click on the links, they work, but left clicking on them does not take you to the page. Nothing happens and no error. If you hard code a model id into the link like so it works:

Route name

But passing a model name in place of the hard-coded id does not work, it merely adds a # to the end of the URL. How can I make this work?




swipe handled by ember-gestures, but also scrolls

I've creates a "touch-list" component for EmberJS, based on ember-collection, with ember-gestures mixed in:

import RecognizerMixin from 'ember-gestures/mixins/recognizers';

export default Ember.Component.extend(RecognizerMixin, {
  recognizers: 'tap press swipe',
...
  swipeLeft(event) {
...
    event.preventDefault();
    event.stopPropagation();

  },
...

My test app has two panels, one for the list and the other for item details. (Slighly out-of-date source code is on GitHub.) On a screen 640px or wider, the container for the panels is set to the viewport width, and all is well - horizontal swipes are recognized, and don't trigger scrolling.

On a screen 639px or narrower, I set the container to twice the viewport width, and each panel to the viewport width. Horizontal swipes on the list header or detail panel scroll, as expected.

The problem is horizontal swipes on list items on touchscreen devices. They are recognized as gestures, and handled by list items, but they also cause horizontal scrolling! As seen above, I call event.preventDefault(); and event.stopPropagation(); but that doesn't help.

How can I prevent swipes from causing horizontal scrolling?




jeudi 30 mars 2017

ember js nested select fields

i have 2 models:

// models\departament.js

        import DS from 'ember-data';
        export default DS.Model.extend({
              name: DS.attr('string'),
              project: DS.belongsTo('project'),
        });

// models\project.js

import DS from 'ember-data';

export default DS.Model.extend({

  name: DS.attr('string'),
  departaments: DS.hasMany('departament',{inverse: 'project'})
});

and template:

// templates\new.hbs

    <select class="form-control" onchange=>

      
          <option class="form-control"  value=""> - </option>

      

    </select>


  <option class="form-control"  value=""></option>


this dont work (( I want that when I select project it will update data in departament select field

I use Json api, how i can use :

"relationships": {
        "departaments": {
          "data": [
            {
              "id": "1", 
              "type": "departament"
            }, 
            {
              "id": "2", 
              "type": "departament"
            }, 
            {
              "id": "3", 
              "type": "departament"
            }
          ], 
          "links": {
            "related": "/api/project/1/departaments", 
            "self": "/api/project/1/relationships/departaments"
          }
        }
      }

sorry for my eng Может есть кто знает русский ?:slight_smile:




in query in Ember JS DS.store model

I have tried below both queries :

    this.store.query('estimate', { 'vendorUids' : supplierData.getEach('vendorUid') } ).then((estimatesData)=>{

});

this.store.query('estimate', { filter : { 'vendorUids' : supplierData.getEach('vendorUid') } }).then((estimatesData)=>{

});

But it is creating query as below :

https://localhost:8080/v1/estimates?vendorUids[]=344&vendorUids[]=5&vendorUids[]=1&vendorUids[]=2&vendorUids[]=3&vendorUids[]=4

I want query to be generated as below like in query :

https://localhost:8080/v1/estimates?vendorUids=[1,2,3,4,5]

Thanks in Advance.




"Assertion Failed: undefined must be a subclass or an instance of Ember.View, not " with no useful info

I started getting this error, but all attempts to debug the reason failed.

The whole info is like this:

Ember.assert    @   ember-1.10.0.debug.js:3940
readViewFactory @   ember-1.10.0.debug.js:39239
viewHelper  @   ember-1.10.0.debug.js:7521
inline  @   ember-1.10.0.debug.js:7948
render  @   VM4480:884
render  @   ember-1.10.0.debug.js:44625
EmberRenderer_createElement @   ember-1.10.0.debug.js:40279
Renderer_renderTree @   ember-1.10.0.debug.js:8768
ensureChildrenAreInDOM  @   ember-1.10.0.debug.js:41922
_ensureChildrenAreInDOM @   ember-1.10.0.debug.js:41885
invoke  @   ember-1.10.0.debug.js:854
flush   @   ember-1.10.0.debug.js:919
flush   @   ember-1.10.0.debug.js:724
end @   ember-1.10.0.debug.js:149
(anonymous) @   ember-1.10.0.debug.js:552

which doesn't help me at all. Nothing is pointing me to the element that is failing, and at the same time a lot of ember elements fail to render.

Any ideas what I'm doing wrong? Or how to find the exact problematic problem?

(Installed Ember inspector which also doesn't help me at all.)




Ember.js component rerender not rerendering

I'm trying to render some data into a table. The data is organized by years, and users can add years to the index.

When the user adds a year, the data for that year is loaded via AJAX and added to an Ember.Object info, like this:

var self=this;
Ember.$.getJSON('url'+year, function(data) {
  var info = self.get("info");
  info['total'][year] = data.total;
  info['commission'][year] = data.commission;
}

In the template, the data is shown via each-in helpers:


  


Following the manual, here, since each-in is not bound to new properties, I added self.rerender(); after the ajax assigments in the component.

My issue is that the component is NOT rerendering. If I change routes and come back, the page is rerendered and the data shows, so the issue is clearly on the rerender() call.

PS: The code shown here is a simplified example; there is a reason why I must use each-in and any solution that necessitates changing the data structure won't help. I just need to know why rerender() is not rerendering and how to make it do so.




add default option to ember power select

in ember power select how to include default options for drop-down like "All" in below enter image description here

my service does't return "All" option.I think it not good to include it in the store.




Remove value from array if it isn't present in another array Javascript

I have an Ember application with which I am building a notification system, if the notification gets dismissed by my user I store the notifications UUID in my cookie so it doesn't get displayed again.

After a month my notifications get deleted from the database, what I am trying to do is check my database and get an array of all the notifications and then compare the UUIDS to my cookies array.

If a UUID exists in my cookies array that doesn't exist in my database I want to delete it from the cookies array.

Here is my code.

this.get('userNotificationServices').fetch().then(allNotifications => {
    if (this.getCookie("dismissed-notifications")) {
        var notificationIdsInCookie = this.getCookie("dismissed-notifications").split(',');
        notificationIdsInCookie.forEach(function (value) {
            var index = allNotifications.findIndex(x => x.id === value);
            if (index === -1) {
                notificationIdsInCookie.splice(index, 1);
            }
        });

        this.setCookie("dismissed-notifications", notificationIdsInCookie);
    }
});

At the moment it seems to be removing the wrong values in the array, for example it removes the last array value instead of the first and then removes every value from the array. Am I doing something wrong with my filtering / is my logic wrong?

Thank you.




mercredi 29 mars 2017

how to bing checkboxes in ember with a list

I have a model where I have a list of all countries as below -

[{"code":"US", "name":"USA"}]

selected counties will be pass on as a list like below -

["US", "CA"]

my template has a list of checkboxes like below -


     
     
       
        <label class="checkbox-inline"></label>
    


the code above doesn't work as intended and I am trying to figure out how to configure the checkbox to achieve what I need. Any ideas?




Page able to be viewed in browser is resulting in 404 when curled

I have a Heroku Ember/RoR application (http://ift.tt/2ocsWt8) that is able to be viewed in the browser, but when I try to curl http://ift.tt/2ocsWt8, I have the following error:

<!DOCTYPE html>
<html>
<head>
  <title>The page you were looking for doesn't exist (404)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  body {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body>
  <!-- This file lives in public/404.html -->
  <div class="dialog">
    <div>
      <h1>The page you were looking for doesn't exist.</h1>
      <p>You may have mistyped the address or the page may have moved.</p>
    </div>
    <p>If you are the application owner check the logs for more information.</p>
  </div>
</body>
</html>

This is further confirmed by Facebook OG Debugger: Facebook Debugger

What's further is that if I do a view source on the page (view-source:http://ift.tt/2ocsWt8) there is nothing in the body tags but javascript files.

What is happening to make it so I'm not able to curl the website or view the contents of the body?




Blink from loading (isPending) to resolved. Why?

This is my ember-twiddle that explain the entire situation:

http://ift.tt/2nhVXP6

My problem is the loading message.

My posts are sideloaded and it can be a very very long time for download.

In the meantime I need to show a loading message (in twiddle this is green).

When I enter the category route from categories route I need the green loading directly, not a blink with red as you can see.

Why it's happening?




How do I use Glimmer components inside an Ember app?

The Glimmer website states:

Just drop your Glimmer components into an Ember app. You won’t need to change a thing.

I’ve been following the official Ember quick start tutorial. I replaced the contents of the generated people-list.js component with this:

import Component from '@glimmer/component';

export default class PeopleList extends Component {

}

and I get an error in the browser console stating that @glimmer/component is undefined. After I run yarn add @glimmer/component to add the dependency, I get a new error from Broccoli.

Additionally, whenever I use '@' before a variable in the people-list.hbs template, the template fails to compile. How do I get the Glimmer component to work in my Ember app?




Ember Data - Serialization Options

I have a model with a hasMany realtionship.

I currently use the EmbeddedRecordsMixin to include the JSONAPI in my payload that is then sent to the server.

My problem is that I wish to send only the JSON representation of this object. i.e without type and attributes hash. Instead I wish to the send the payload as simply JSON { id: 1, Name: 'Darren', Surname: 'Blh' ... }

How is it possible to convert the JSONAPI to JSON?

Thanks

Darren




EmberJS router and external library

I have currently difficulties in using the EmberJS router and an external library. Using the EmberJS router, the routing functionality works perfectly. Also the inclusion of the external library within a component works as expected.

BUT the combination of both is not working.

In detail: the library (pdf.js) is manipulating the DOM and inserting anchor tags while scrolling through the document. These anchor tags work fine. But if I try to "catch" the event and use the EmberJS routing functionality, it is not working! I cannot create an eventlistener in the DidRender() function and use preventDefault, because the elements are not present during the time of execution of DidRender.

Did anyone face the same issue or maybe has a solution for this problem?

Cheers, Franz




Ember: Does Ember Data handle delayed record creation

I am building an Ember app against an api that has an endpoint for creating a resource via a queue.

When I send the POST to the endpoint it will respond with a 202 Accepted if the parameters are okay, then add the actual work to create the record to a queue. No id is returned because the backend doesn't have one yet.

I'm just wondering if there is a means of using the Ember Data store to save records for this case. I can see how not returning an id would be problematic, but since 202 Accepted has semantic meaning in JSONApi, I was curious whether Ember Data handles this somehow.

Right now I am simply calling the adapter's createRecord function directly instead of using the store.




is it ok to use jquery inside ember controller or component

I wanted to follow ember js rules thoroughly.but I am novice to ember js so I am struggle to find ember standard way of doing coding.

Is it ok to do some jquery code inside ember component or controller ?

is it not good to use jquery inside there ?I think it not good to use jquery there.




ember js pragmatically set selected option

This is my sample drop down

<select name="newType" class="parts-select full-width-combo" onchange=>
            <option value="" selected  hidden >Select </option>
            
                <option value=""></option>
            
 </select>

from the relevant template action I wanted to set this selected item dynamically.

As an example it default selected by "Select" and then based on some button click on that page and need to set my selected option to other selected option to be selected. I am not using any plugin and I can't do it here.




Ember syntax errors

I am learning ember.js with a tutorial that is built in to their documentation. Having installed it successfully, I followed the steps and created a new application with ember new ember-quickstart, generated a template and defined a route. However, the data that I've included in the route model is not being rendered (there appears to be a parsing error due to an unexpected token default), but I have no idea what it might be referring to. I have pasted the code exactly as it appears. Any suggestions as to what might be causing the error?

SyntaxError: ember-quickstart/routes/scientists.js: Unexpected token (3:2)  

enter image description here

routes/scientists.js

import Ember from 'ember';

  default Ember.Route.extend({
  model(){
    return['Marie Curie', 'Albert Einstein', 'Andrei Sakharov']
  }
});

templates/scientists.hbs

<h2>List of Scientists</h2>

<ul>
  
  <li></li>
  
</ul>

templates/application.hbs

<h2 id="title">Welcome To Ember</h2>



app/router.js

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

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

Router.map(function() {
  this.route('scientists');
});

export default Router;




mardi 28 mars 2017

From firebase storage download file to iframe

With below code, I can not download image to iframe. Instead, it downloaded to local drive.

in JS:

  storageRef.child('images/CopyPerson.jpg').getDownloadURL().then(function(url) {
  var iframe1 = document.getElementById('downloadedCourse');
  iframe1.src = url;
}).catch(function(error) {
  // Handle any errors
});

in html:

  <iframe id="downloadedCourse" width="800" height="500" src=""></iframe>

However, if I use img instead of iframe, it works as supposed. The reason I need use iframe is because I intend to download pdf file. Anyone knows why?




findAll throwing error

I am using a simple findAll query in my ember application ( ember-version: 2.12.0, ember-data-version: 2.12.1 ) and I get the following error:

Assertion Failed: You can no longer pass a modelClass as the first argument to store.buildInternalModel. Pass modelName instead.

I am using the RESTAdapter and RESTSerializer.

Here is my team model:

import DS from 'ember-data';

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

  projects: DS.hasMany('project'),
  users: DS.hasMany('user'),
  members: Ember.computed('users', function() {
    return this.get('users.content.length');
  }),
  leader: DS.belongsTo('user', {
    inverse: 'team'
  })
});

and my team serializer:

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

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin,{
  attrs: {
    users: { async: true },
    projects: { async: true }
  }
});

Despite the error, the team objects I requested are in the store. I had no luck in solving this so far.




Finding the number of records returned from a conditional statement in ember

I have a unless condition and I want to find out the number of records that satisfies this unless condition.

Can do this or not in ember?




How translate serialize type with dash to model slashed structure?

My API in Rails with AMS (JSON:API) return from serializer the type name with dash (artemis-forum-disputes), but inside my frontend app, who uses Ember, I store my models with subdirectory structure (artemis/forum/disputes).

WARNING: Encountered a resource object with type "artemis-forum-disputes", but no model was found for model name "artemis-forum-dispute" (resolved model name using 'apollo-enterprise@serializer:application:.modelNameFromPayloadKey("artemis-forum-disputes")').

How solve this? Thanks.




How to upload image through form into public folder directly in ember js.

<input
  multiple="true"
  onchange=
  accept="image/png,image/jpeg"
  type="file"
/>

actions: {
  upload: function(event) {
    console.log('upload');
  }
}

So how do I save the event to a certain url say '/Images/Picture_collection'




Transition to route's action from Ember object

I am fairly new to ember. I have an existing Ember App and i need to implement a functionality in it. I have a Ember Object as below

`import Ember from 'ember'`

CallService = Ember.Object.extend

 ... other code here

 _updateConnectedLeadId: (->
    console.log "Do i get here??"

    **pass the route action here**

  ).observes('some_other_here')
`export default CallService`

Unfortunately, i couldn't put the whole code here.

My route looks like

ApplicationRoute = Ember.Route.extend
  actions:
    showLead: ->
      console.log data
      console.log "did i get here?"
      @transitionTo('dashboard')

`export default ApplicationRoute`

I tried using @send('showLead'), @sendAction('showLead') in my method but no luck.

My main intention is to make a transition once the console.log "Do i get here??" is displayed. I am not sure if i am on the right way here.

I also tried using @transitionTo('dashboard') and @transitionToRote('dashboard') directly but it throws me errors.

I have been stuck for a day on this now and i am clueless.

I'll be grateful for any guidance and help. Thanks




Deleted records are not accessible

Given a model parent, that hasMany childs.

How can I track deleted childs? If ember keeps track of them, how I access them?

I have a complex form, where user can add/edit/delete childs, but we have only one place to persists/cancel the parent. Is in this place where we persist/rollback also the childs.

I can manually keep track of deleted records, but if Ember keeps track of them, I prefer to use ED ;-)

I'm playing with something like that, but it's not working:

dirtyTasks: Ember.computed.filterBy('model.childs.@each.content', 'isDirty', true),
deletedTasks: Ember.computed.filterBy('model.childs.@each.content', 'isDeleted', true),
changedTasks: Ember.computed.union('dirtyTasks', 'deletedTasks'),


dirtyTasks: Ember.computed.filterBy('model.childs.@each', 'isDirty', true),
deletedTasks: Ember.computed.filterBy('model.childs.@each', 'isDeleted', true),
changedTasks: Ember.computed.union('dirtyTasks', 'deletedTasks'),


dirtyTasks: Ember.computed.filterBy('model.childs.[]', 'isDirty', true),
deletedTasks: Ember.computed.filterBy('model.childs.[]', 'isDeleted', true),
changedTasks: Ember.computed.union('dirtyTasks', 'deletedTasks'),

Also, in the inspector, I can see the content.canonicalState, content.currentState, wich are arrays with the rows, but sure there is an easier way like: model.get('childs.deletedRecords') or something similar ?

thanks

Same question but it's not clear to me how to solve it




lundi 27 mars 2017

How to exclude files from Ember build?

I have a project build on Ember that uses ember-engines library.

My goal - is to exclude some files from in-repo-addons (engines).

I tried ember-cli-funnel. It allows to exclude files from the application but not from engines.

var app = new EmberApp(defaults, {
  funnel: {
    enabled: true,
    exclude: ['app-name/templates/components/develop/**']
  }
});

The example of the project structure:

    ├── app/
    │   ├── controllers/
    │   ├── routes/
    │   └── templates/
    │       └── components/
    │           └──develop/
    └── lib
        ├── engine-1
        ├── engine-2
        └── engine-3
            └── addon/
                └── services/
                    └──debug.js

I tried different ways to exclude but with no luck.

[
  'lib/engine-3/addon/services/debug.js',
  'app-name/http://..lib/engine-3/addon/services/debug.js',
  'app-name/addons/engine-3/addon/services/debug.js'
]

So the question - how can be excluded files from in-repo-addons on build step?




How to check if ember model has key

I'm using ember data since long time but I never had a situation to check if there's a key present in the model. Generally, I check if there's a value present for a key in the model as

if(model.get('keyname')) { console.log('value present') }

But now I want to check if there's a key present in the model object. Any help would be appreciated.




Issue with Ember Binding Style Attributes

I feel like I'm following the documentation but I must be doing something wrong. Would love your help.

In my template, I have:

<div style="">

In my component js file I have:

backgroundImage: Ember.computed('background-image', function() {
  var imageUrl = this.item.attributes.imageMain.url;
  return Ember.String.htmlSafe('background-image: url('+ imageUrl +')');
})

Things are working fine, but I'm still getting the warning in the console:

WARNING: Binding style attributes may introduce cross-site scripting vulnerabilities; please ensure that values being bound are properly escaped. For more information, including how to disable this warning, see http://ift.tt/1gF7OUZ.

Would love any help / second eye. Thanks so much!!




Dynamically define properties to Ember Data model

I'm working on a data model that has a set of predefined attributes that will always be present, and other custom properties defined for it by the user.

A company has many roles. Each company using this system will want to define custom properties for all its roles, in addition to the fixed set of properties that all roles have across different companies.

The idea would be that then roles payload in json-api come with all the attributes, custom or not:

{
  "id": "123",
  "type": "roles",
  "attributes": {
    "name": "CEO",
    "salary": 100000,
    "favoriteColor": "blue"
  }
}

In the above role, name and salary are default attributes, present in all roles regardless company, but favoriteColor is a custom attribute that the particular company owning this role defined as something that they needed to have for all its roles.

I'm wondering if I could get away with something like this using Ember Data, given that I won't be able to define these custom attributes in the role model definition:

// app/models/role.js
export default DS.Model.extend({
  name: DS.attr('string'),
  salary: DS.attr('number'),
})

To make matters even worse, the idea is that these custom attributes will not necessarily be string values, but they can have their type specified too. So a company may want to have favoriteColor of type string, and also birthDate of type date.




dimanche 26 mars 2017

Ember: Nothing Handled the Action Error Occured

So I'm following a tutorial to build an app on CodeSchool and I was trying to figure out how to write in a toggle when I noticed an error in the console basically saying that nothing is handling the action block I wrote in the template.

"Nothing handled the action 'toggleOption model option'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble."

The code below is the part of the template I'm having trouble with.

<ul class='list list--answer'>
            
              <li class='list-item'>
                <button class='list-item-checkbox ' >
                  <b class='srt'>Select</b>
                </button>
                <span></span>
              </li>
            
</ul>

This is the route associated with the template.

import Ember from 'ember';

export default Ember.Route.extend({
store: Ember.inject.service(),
model(){
    const poll = this.modelFor('polls.poll');
    return this.get('store').createVote(poll);
},
actions: {
    toggleOption(vote,option){
        vote.toggleOption(option);
    }
}
});

Anyways, is there something I'm missing? I've been staring at this for awhile and I couldn't figure this out. The tutorial video I've been following and their completed code doesn't seem to run into this issue either.




Ember 2, Strange behaviour with isPending, isSettled, isFulfilled when using included relationships in API response

I need to understand once for all why property like

isSettled isPending isFulfilled

are different if I'm including or not the data in my API respone.

I'm asking here this: http://ift.tt/2n6Za4d which leads me to this strange behaviour:

If I include in my API responde the data (ex: model.posts) these properties are immediately set to true (and .isPending to false) also if Chrome is still loading the real data (also for the first time!).

And this is a problem because I don't know if the posts[] are empty or not and I don't know what I can spy because something like that doesn't work:


  My posts.

  
    <div>Loading...</div>
  
    <div>Nothing to show.</div>
  


It's always "Nothing to show." until Chrome loads. Because .isPending is immediately false.

Also if I use the length attributes:

because the starting posts[] array and the empty one is always to length == 0.

If I loads posts differently, async, not sideloaded (but with hundreds HTTP requests, which I don't want) it works. Ember recognize an isPending...

Why this strange behaviour?




Ember 2, Show a single loading message when the ids where included in the original response

I use very often in my code:



  <div>post.title</div>



  <div>I'm loading the posts...</div>



But sometimes I don't know if the model.posts is empty or not.

How to show a message instead of loading forever an empty array?

The problem here is that I'm in /category/2 page, so in category.hbs template and posts are "sideloaded" in response, like this:

{
  "data": {
    "id": "1",
    "type": "categories",
    "attributes": {
      "name": "Books"
    },
    "relationships": {
      "posts": {
        "data": [{
          "id": "14",
          "type": "posts"
        }, {
          "id": "15",
          "type": "posts"
        }, {
          "id": "20",
          "type": "posts"
        }]
      }
    }
  },
  "included": [{
    "id": "14",
    "type": "posts",
    "attributes": {
      "commented": true,
      "comments": 10
    }
  }, {
    "id": "15",
    "type": "posts",
    "attributes": {
      "commented": false,
      "comments": 10
    }
  }, {
    "id": "20",
    "type": "posts",
    "attributes": {
      "commented": false,
      "comments": 10
    }
  }]
}

I'm using ember-data and my models are:

category

name: DS.attr('string'),
posts: DS.hasMany('post')

post

commented: DS.attr('string'),
comments: DS.attr('number'),
category: DS.belongsTo('category')

Maybe I will create an ember-twiddle, I'm having problem to simulate my problem with ember-data on ember-twiddle...




samedi 25 mars 2017

Set focus on a text box in ember js

I am trying to change a text to a text box. If a user clicks the text, it will change to a test box and so they can edit the content. I have done that. I am able to set the focus by below code.



It only works for the first time. If I focus-out, the text box will again change to text content. If I click the text again, I am able to see the text box, but it is not in focus. Below is the code I am trying.

Component file:

import Ember from 'ember';

export default Ember.Component.extend({
  isTextBox: false,
  actions: {
    editTest() {
      this.set('isTextBox', true);
    }
  },
  focusOut() {
    this.set('isTextBox', false);
  },
});

Template file:


<center><h2>
<div onclick = >





</div>
</h2></center>

I am new to ember and I trying to do the focus without using jQuery.

Here is the twiddle http://ift.tt/2nnHmVz.




how to call action of route from component?

i have button in component

<button type="button" class="btn btn-sm btn-default" >GO</button>

Now i have written this action applyDateFilter in component.js like this

applyDateFilter() {
            var variable = this.get('dateFilter');
            this.sendAction('testAction2');
        }

Now i have another action in main route.js file

testAction2: function(){
            alert('test');
        }

Now i want to call this route action from applyDateFilter action so how can i do this.I am using ember js version 2.10. Thanks




How to include ember-template-compiler.js when using ember-source

After migration to node ember-source from bower ember package our build is failing with missing ember-template-compiler.js which was part of the bower package. How to include it from ember-source npm package.




vendredi 24 mars 2017

Ember JS how to implement a normal ES6 class

I'm new to Ember and I'm having an issue with understanding exactly where "reusable" code should go. From what I've found so far, it sounds like this is supposed to be a utility? The only issue I have no idea how to include the class (or any reusable methods) into the controller.

Here's what I'm after

Example class (where would this go?):

'use strict'

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    getPerson(){
        return "My name is " + this.name + " and I'm " + this.age + " years old";
    }
}

/app/routes/index.js:

import Ember from 'ember';
export default Ember.Route.extend({
    beforeModel(){
        this.replaceWith('rentals');
    }
});

/* How would I include the class so I could call the below??
    var person1 = new Person('Bob', '15');
    var person2 = new Person('Kevin', '41');
    console.log(person1.getPerson());
    console.log(person2.getPerson());
*/




Choice of Front end Framework for an application

I would appreciate if answers - strictly - do not make comparisons and stick to one framework which a person uses - so that opinions are not propagated!

I would like more specific information regarding -
what kind of hammer a given framework is!

I tried to search on the web regarding front end frameworks to use for making an application but there are too many diverging viewpoints.

At a given point in time there is hype around a frontend framework, but it does not serve well to a newbie who is trying to find the correct answer. Therefore, I hope the answers to this question will be more matter of fact ones and strictly related to one single framework which a person uses!

Specifically, I would like information related to -

  1. Angular 2
  2. React + Redux
  3. React + X (any)
  4. Backbone + Marionette
  5. Ember
  6. Vue
  7. Any other which you were very productive with!

If you have used any of these, your experience with them can be useful in another person's decision regarding choice of a framework, thanks.




Ember 2, Show message for an empty model instead of loading in hbs template, each or if

I use very often in my code (and I don't know if I'm right to use it):



  <div>post.title</div>



  <div>I'm loading the posts...</div>



and until today everything OK.

But now I don't know if the model.posts is empty or not.

How to show an error instead of loading forever an empty array?




Click in acceptance test during continuous Ember.run.later

In the controller I have Ember.run.later loop, which continuously updates the timer.

run: function() {
    const lastResumeTimestamp = this.get("lastResumeTimestamp");
    this.clearTimer();
    this.set('timerId', Ember.run.later(this, function() {
    // update the timer  
    // ...
      this.run();
    }, 100));
  },

In acceptance test I want to click button, which should pause this loop:

test('I want to start/pause new activity', function(assert) {
  visit('/');
  andThen(function() {
    assert.equal(find('.duration', activityBuilderSelector).text(), "0");

    click('.start-activity-button', activityBuilderSelector);
    // -->> start continuous Ember.run.later.loop, see: application cortroller

    waitFor(assert, function() {
      const val = find('.duration', activityBuilderSelector).text()
      assert.notEqual(val, "0", `notEqual 0 (${val})`);
      assert.equal(find('.title', activityBuilderSelector).text(), "New activity", "there should be activity title");
      // -->> here test waiting because of run.later loop
      click('.pause-activity-button', activityBuilderSelector);
    });
  });

  andThen(function() {
      //click('.resume-activity-button', activityBuilderSelector);
  });
});

but test pause before the click and waiting for loop stop.

How can I trigger this click during loop and stop it to continue test?

Here is little twiddle which demonstrate this issue: http://ift.tt/2mz2J7S




Computed property don't observe changes in objects in array

My component don't observe changes in my array of objects, when i change language. It works only after change route, but it's deserved to change everything immediately, without reload page.

Component code:

  columnsToEdit: Ember.computed('i18n.locale', function() {
    let i18n = this.get('i18n');
    return Ember.A([
      {
        "propertyName": "name",
        "title": i18n.t('Name')
      },
      {
        "propertyName": "phone",
        "title": i18n.t('Name'),        
      },
    ]);
  }),

  columns: Ember.computed.map('columnsToEdit.[]', function(column){
    return column;
  }),

I think, it should works. "ColumnsToEdit" looks for changes from i18n.locale in "columsToEdit". Next "columns" looks for changes in "columnsToEdit". When I call "console.log" in "columns" it returns expected result, but in my view nothing happened after click "language-switch". So why my component didn't change "titles" in view? Any help will be appreciated.




application level component property change

I need to change the layout componet value from page level template.

enter image description here

like in picture x.hbs may vary according to route.each spesific route may have add to cart button and when add to cart button click the layout component price should be updated.

how to do something like this in emberjs way?




Ember Data and each loop and nested objects in Handlebars

I have an issue when trying to display a list of objects where each object has nested objects and there is even another level of objects in those objects. The API-respons gives me this (simplified) JSON-data where there are many freight orders:

{
    "freightOrders": [{
        "id": 1,
        "comment": "Freight order comment",
        "shipments": [{
            "id": 1,
            "shipment_lines": [{
                "id": 1,
                "description": "A description",
                "package_weight": 900,
                "package_length": 1200,
                "package_height": 400,
                "package_width": 800
            }],
            "pickup_address": {
                "id": 1,
                "address": "The pickup address",
                "zip": "9000"
            },
            "delivery_address": {
                "id": 2,
                "address": "The delivery address",
                "zip": "8000"
            },
        }],
    }]
}

What I want is to display a list of all freight orders, and for the time being, access directly the first shipments-line for each order. In Handlebars I have tried


    <span>
        ,
        
    </span>


and


    
        <span>
            ,
            
        </span>
    


Whatever I try to do, I am not able to access shipments element or any nested objects of the order object.

I can mention that I have also tried to create the shipments part as a component and pass order.shipments to the component, but to no prevail.

Searching SO and google does not reveal any hints only some examples of how to do nested each in ember 1.x

So, how can one access nested objects in an each-loop in Handlebars and Ember Data?




Cannot find module: Ember-template-compiler after upgrading to 2.12.1

After upgrading to Ember cli 2.12.1 I receive the following error, when trying to serve ember.

Cannot find module 'C:\Users\assaue\web\client\bower_components\ember\ember-template-compiler'
Error: Cannot find module 'C:\Users\assaue\web\client\bower_components\ember\ember-template-compiler'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Class.htmlbarsOptions (C:\Users\assaue\web\client\node_modules\emberx-file-input\node_modules\ember-cli-htmlbars\ember-addon-main.js:72:25)
    at Object.toTree (C:\Users\assaue\web\client\node_modules\emberx-file-input\node_modules\ember-cli-htmlbars\ember-addon-main.js:31:43)
    at C:\Users\assaue\web\client\node_modules\ember-cli-preprocess-registry\preprocessors.js:180:26
    at Array.forEach (native)
    at processPlugins (C:\Users\assaue\web\client\node_modules\ember-cli-preprocess-registry\preprocessors.js:178:11)
    at module.exports.preprocessTemplates (C:\Users\assaue\web\client\node_modules\ember-cli-preprocess-registry\preprocessors.js:161:10)




Using inline "if helper" with logical operator in Ember

So basically, I just want to add class active if index is equal to 0.


  <div class="item add active class here if index is 0">
  </div>


I know using this code, won't work because built-in if helper in ember doesn't support logical operators. Ember Conditionals

So what are the ways to achieve this?




Reading error status code in response header in ember

In my app I want to render some images.for that I am setting the path in my img src attribute.This will make a call to the server and on success the response is set to src attribute and the image is rendered.In some cases the server may respond with errors in response headers with status codes like 400,401,404,500.on error i will display a default image.I have handled this with onerror, onload methods.It is working perfectly in displaying default images onerror.But I want to read the status code on response headers in onerror method to differentiate between the errors.May I know how can i read the status code in response header?

image model file:

    import Ember from 'ember';  
    import DS from 'ember-data'; 
    export default DS.Model.extend({
    image_url:DS.attr(),
    is_image_created: computed('image_url', function(){ 
            let img = new Image(),
                self = this,
                url = "/api/image/"+self.get("id"); 
            img.onerror = img.onabort = function() {
                self.set("is_image_created", false); 
            };
            img.onload = function() {
                self.set("is_image_created", true); 
            };
            run.later(function(){
                img.src = url;
            }, 3);
        }),
    });

displayimage.js---route file

import Ember from 'ember'; 

const { Route} = Ember;

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

displayimage.hbs


                <img src="/api/image/"+model.id>
            
                <svg class=" inline-block zdicon-26">
                     <use xlink:href="#icon-"> </use>
                </svg>
            

Thanks in advance.




jeudi 23 mars 2017

In an Ember framework, How do I remove the Pod folder name from the URL

I'm using Ember POD syntax to organize my Ember application.

picture of files organized under POD directory named 'main'

Is it possible to remove the pod directory from appearing in the browser URL? If so, how?

See picture.

picture of the pod directory in the URL path

Thanks.




Ember: How do I get simple form data without a model?

I'm trying to do get a single string from a form input and log it to the console. Is there a way to do this without using an Ember Data model?

Here's the form component in Handlebars:

// my-form.hbs
<form >
  
  <button class="btn btn-primary">Get Early Access</button>
</form>

And here's the current code from the component:

// my-form.js
import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    grabNewEmail() {
      let email = /* I want to get this string from the input on submit */
      console.log(email);
    }
  }
});

Is it possible to simply grab the input string, or am I required to create a model?

Thanks!




onClick action not working in Route in EmberJS

I have a button which increase the value of quantity. i wrote the onclick action to increase the value of this quantity in the route.But this does not work, the onclick in not working and this does not give out a error as well.

i am new to EmberJS so please help.

This is the code which i tried.

My route.js

  actions: {
    increaseRequiredQuantity() {

        debugger;
        $('.qtyplus').click(function (e) {
            e.preventDefault();

            fieldName = $(this).attr('field');

            var currentVal = parseInt($(this.parentElement).find('input[name=' + fieldName + ']').val());
            var currentNewVal;

            if (!isNaN(currentVal)) {
                currentNewVal = currentVal + 1;
                $(this.parentElement).find('input[name=' + fieldName + ']').val(currentNewVal);
            } else {

                $(this.parentElement).find('input[name=' + fieldName + ']').val(0);
            }

        });
    }
}

this is how am calling the action from the template

<button type="button" class="btn btn-default btn-number qtyplus" data-type="plus" field='quantity' id="btnIncrease"><span class="glyphicon glyphicon-plus"></span></button>




Ember qunit assert.throws does not work

I installed Ember 2.12 and created new project with a component and a test to ensure it throws an error if required attribute is not provided. I can't get this test to pass.

dummy-component.hbs




dummy-component.js

import Ember from 'ember';
export default Ember.Component.extend({
  value: Ember.computed(() => {
    Ember.assert("Someone forgot to provide a required value attribute");
  })
});

dummy-component-test.js

import Ember from 'ember';

export default Ember.Component.extend({
  value: Ember.computed(() => {
    Ember.assert("Someone forgot to provide a required value attribute");
  })
});

Test fails with the following:

    ---
        actual: >
            false
        expected: >
            true
        stack: >
            exception@http://localhost:7357/assets/test-support.js:7664:49
            adapterDispatch@http://localhost:7357/assets/vendor.js:50288:22
            dispatchError@http://localhost:7357/assets/vendor.js:28557:23
            invokeWithOnError@http://localhost:7357/assets/vendor.js:10921:14
            flush@http://localhost:7357/assets/vendor.js:10977:15
            flush@http://localhost:7357/assets/vendor.js:11101:20
            end@http://localhost:7357/assets/vendor.js:11171:28
            run@http://localhost:7357/assets/vendor.js:11285:19
            run@http://localhost:7357/assets/vendor.js:33262:32
            render@http://localhost:7357/assets/test-support.js:8538:30
            http://localhost:7357/assets/tests.js:129:19
            throws@http://localhost:7357/assets/test-support.js:4609:17
            http://localhost:7357/assets/tests.js:128:18
            runTest@http://localhost:7357/assets/test-support.js:3696:34
            run@http://localhost:7357/assets/test-support.js:3682:13
            http://localhost:7357/assets/test-support.js:3860:15
            process@http://localhost:7357/assets/test-support.js:5094:26
            begin@http://localhost:7357/assets/test-support.js:5077:11
            http://localhost:7357/assets/test-support.js:4294:11
        message: >
            Error: Assertion Failed: Someone forgot to provide a required value attribute
        Log: |
            { type: 'error', text: 'null\n' }
    ...

whole process took less than 5 min

npm install -g ember-cli
ember new ember-test
ember g component dummy-component
<copy.paste> template, js and the test
ember test




How to bind computed property with classNameBindings in Ember 2.x

There is no doc on how to bind computed property for classNameBindings.

  classNameBindings: ['isChecked'],

  isChecked: computed('selected', {
    get() {
      return this.get('selected').includes(this.get('row'));
    }
  }),

Code above does not trigger computed property.




How to remove logic from template?

For example, I have created a multi-selection list,

In the controller,

import Ember from 'ember';

export default Ember.Controller.extend({
  options: [
    'AAAAA',
    'BBBBB',
    'CCCCC'
  ],

  selected: []
});

Multi-selection component template,

<ul>

  <li  class="">
    
  </li>

</ul>

Component's JS,

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    addSelection(option) {
      const selected = this.get('selected');
      if (selected.includes(option)) {
        selected.removeObject(option);
      } else {
        selected.addObject(option);
      }
    }
  }
});

As you can see, in code snippet #2 there is some sort of logic inside the template,

<li  class="">

I would love to remove the logic from the template because,

  1. It makes the component hard to maintenance
  2. Logic inside the template cannot handle complex data structure

Any suggestion is appreciated.




Ember.js: How to prevent refreshing nested routes?

What's the Ember way to refresh middle route's model when query params changed? I could use something like this

queryParams: {
  qParam: {
    refreshModel: true
  }
}

in middle route, but it calls route's refresh function a refresh also its nested routes and it's inappropriate for me.




mercredi 22 mars 2017

In Chrome, while dragOver, can dragged object be identified as file or directory

Using Ember.js 2.7, in Chrome browser, while dragging files or folders from outside the browser, can we detect objects type weather its a file or folder.

Pls Note: We can detect it in drop event, my requirement is to do so while objects are being dragged, so that I can set the "Not Allowed" sign at drag time.




How to access queryParams in ember when locationType is set to hash

I've queryParams:['qp1','qp2'] in my application controller and in the model hook I've something like below

model : function(params) {
    console.log(params.qp1);
    console.log(params.qp2);
}

Everything above is working fine if the locationType is set to auto in my environment.js file but when I set the environment to hash, both are undefined. I'm able to see the params object as

params:{
      qp1:undefined,
     qp2:undefined
}

I'm wondering why I'm able to access queryParams when the locationType is auto but not when locationType is hash




Template is not refreshing on object property change (Ember 2)

I'm running into an issue with Ember where when I change a property of an object (in this case filteredHeroes) and then set the computed property to be the updated version, my template does not update. How can I force the template to update with the change to the object when the action is called?

In my template, I have:





In my controller I have an action:

calculateStats() {
        var heroes = this.get("filteredHeroes");

        var valueOfAttackSpeedPerCP = 5.5;
        var valueOfPowerPerCP = 6;

        var attackSpeed = this.get('cpAttackSpeed') * valueOfAttackSpeedPerCP;
        var power = this.get('cpPower') * valueOfPowerPerCP;

        for (var i = 0; i < heroes.length; i++) {
            //Set Attacks per second for the specific hero
            heroes[i]._data.AttacksPerSecond = (1 / (heroes[i]._data.attributesByLevel[14]['BaseAttackTime'] / ((heroes[i]._data.attributesByLevel[14]['AttackSpeedRating'] + attackSpeed) / 100)));   
        }
        this.set('filteredHeroes', heroes);
    }

Thanks for any help!




Ember destructing function

I see often come across code in Ember.js that use object destructing to retrieve a function

const { computed } = Ember;

If there is advantage to this pattern instead of calling Ember.computed directly other than reduce the code? Would this go against encapsulating functions in objects?




How set short month names using ember-moment

I need to change short month in moment. But I can't do it. I have try to set

localeOutputPath: 'assets/moment-locales'

And call

Ember.$.getScript('/assets/moment-locales/ru.js');

In this case i have ember-mirage error

 Your Ember app tried to GET '/assets/moment-locales/ru.js?_=1490191145335',
 but there was no route defined to handle this request. Define a route that
 matches this path in your mirage/config.js file

Is it simple way to set short months name for moment?




ember multiple component with various id

i has a component in ember i named it foo

import Ember from 'ember';
var data, elTop;
export default Ember.Component.extend({
  init(){
    this._super(...arguments);
  },
  didInsertElement(){
    this._super(...arguments);
    data = this.get('id');
    elTop = $('#'+data).offset().top;
    console.log(elTop);
  }
});

btw, i using this component twice in parent template and the position of each component is diferent, but why when iam console log the offset top the value its same.

can anyone explain this and solved it? and i avoid using this console.log($('#'+data).offset().top) its work but show glitch when i using on scroll event.

thankyou :)




mardi 21 mars 2017

Ember data Error: the adapter's response did not have any data

I just upgraded an app from Ember 1.13 to Ember 2.12. Now my attempts to load the data store are failing. This line:

return this.store.find('blog', 14);

generates this error: "Error while processing route: blogs.index Assertion Failed: You made a findRecord request for a blog with id 14, but the adapter's response did not have any data".

But the data is arriving, and in this format:

{ "blogs": { "id": 14, "person_id": "1", "access": "3" } }

My adapter is specified in application/adapter.js as:

export default DS.RESTAdapter.extend({

host: "http://localhost", namespace: 'api-rick'

});

Anyone know why I'm getting this error? I think the JSON is properly formatted -- didn't have any problems before I upgraded Ember.




Ember 2.11+ can't find `ember-template-compiler` after removing ember from bower

Since Ember version 2.11, it should be possible to remove ember from bower, and instead load the library using the npm ember-source module.

I've run npm install --save-dev ember-source. I've removed ember from the bower.json file, and run rm -rf bower_components/ember. I've added ember-source to packages.json and installed it .

When I run ember serve, it fails with this message:

Cannot find module 'path/to/myapp/bower_components/ember/ember-template-compiler'
Error: Cannot find module 'path/to/myapp/bower_components/ember/ember-template-compiler'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Class.included (path/to/myapp/node_modules/ember-cli-htmlbars-inline-precompile/index.js:48:20)
    at Class.superWrapper [as included] (path/to/myapp/node_modules/ember-cli/node_modules/core-object/lib/assign-properties.js:34:20)
    at EmberApp.<anonymous> (path/to/myapp/node_modules/ember-cli/lib/broccoli/ember-app.js:495:15)
    at Array.filter (native)
    at EmberApp._notifyAddonIncluded (path/to/myapp/node_modules/ember-cli/lib/broccoli/ember-app.js:490:45)
    at new EmberApp (path/to/myapp/node_modules/ember-cli/lib/broccoli/ember-app.js:140:8)

It looks like ember is trying to load ember-template-compiler from the bower module, which no longer exists. How can I tell ember that it should instead be looking for node_modules/ember-source/dist/ember-template-compiler.js?




Upgrading to liquid-fire 0.27.1 breaks velocity

My app works fine with liquid-fire 0.26.x and ember-cli 2.11.x, when I upgrade to the latest cli version, 2.12.0, liquid-fire 0.26.x throws errors. The errors are removed when I upgrade liquid-fire to it's latest release, 0.27.1.

However, although the app loads, the app is broken as my velocity animations no longer work and I receive the following error in my browser console:

Velocity: First argument (transition.slideLeftIn) was not a property map, a known action, or a registered redirect. Aborting.

Any thoughts as to why this is happening?




How to transition to the same route from a component in EmberJS

I have a main template say showcountry.hbs , inside that I am having a component show-state.hbs. In show-state.js I have tried putting "this.transitionTo('routename')" . I see that it works for routes other than showcountry . Complicating thing slightly is that in my router.js the entry looks something like the following " this.route('showcountry' , {path : '/app/mod/country' });

I find that in component when I give the URL pattern in this.transitionTo it throws unrecognized URL error .

Please help.




Remove array elements based on dynamic value Javascript

I have 2 arrays within my Ember application, one array holds a string of ID's and another holds Ember objects.

I want to send the Ember objects to a function, get the array of ID's from a cookie stored in the browser and then filter out the Ember objects if the ID property corresponds to a string in my array of IDS.

I am attempting to use filter for this but every time it just brings back the full list of Ember objects, even if there ID is held in the ID string array. Here is my code from my Ember component..

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

this.get('userNotificationServices').fetchActiveUserNotifications().then(result => {
            this.updatedArray = this.filterArray(result);
            this.set('activeNotifications', result);
        });

    },

filterArray(currentActiveNotifications) {
    var ids;
    var currentNonDimissedNotifications;
    if (this.getCookie("dismissed-notifications")) {
        ids = this.getCookie("dismissed-notifications").split(',');
        currentNonDimissedNotifications = currentActiveNotifications.filter(function (obj) {
            for (var id in ids) {
                return obj.id !== id;
            }
        });
    }
    return currentNonDimissedNotifications;
}




Using Ember with MaskedInput and Validated Form

I want to do a form that is validated in the client side. So, I used the ember-validated form. I want to add some masks to inputs.

Is it possible to make input with validated-form and add to it a mask ?






lundi 20 mars 2017

Ember.js - Update view only if my data is upload into the server

I just want that my view doesnt update anything (when i create me new task) until the data is upload it into the server

actions: {
  addTask: function(){

    var title = this.get('title');
    var description = this.get('description');
    var date = this.get('date');


     var newTask = this.store.createRecord('task',{
         title: title,
         description: description,
         date: isValidDate
       });


       var self = this;
       //Save to firebase
       newTask.save().then(function(){

            //clear Form after update database
          self.setProperties({
            title: "",
            description: "",
            date: ""
          });
        });

     }

  }

and this is my view

<h1>Tasks</h1>

  <div class="well">
    <h4> </h4>
    <small>Due: </small>
    <p></p>

  </div>


i try to to add {backgroundReaload: false} in the route but i think that i misunderstood for what is for

model: function(){
    return this.store.findAll('task',{ backgroundReload: false });
  }




Installing ember-3d-orbit-controls getting error "spawn undefined ENOENT"

Error Image

I am working on xampp, i am using ember 3D addon. On installing "ember install ember-3d-orbit-controls" i am getting error "spawn undefined ENOENT".

Thanks in advance

please tell me the another way of user 3d-orbit-controls ad-dons with the ember js server




Dynamic component not rendering when passed into child component

I am trying to pass in a component constructor to a child component, but when I do I get an error message: Assertion Failed: A helper named 'parent.section' could not be found

//parent-form.js
form-component as |f|
  ...
  child-component f=f

//child-component.js
f.group as |g|
  ...

//form-component.js
with (hash group=(component 'form-section-component')) as |h|
  yield

The strange thing is if I delay the parent.group call everything works fine. For example:

//child-component.js
if isShowingFormSection
  f.group as |g|
    ...

When isShowingFormSection changes to true, parent.group gets called and renders just fine.

Does this mean the template is trying to instantiate the component before the component is ready?




Ember load-initializers error: Could not find module `ember-load-initializers`

I'm having trouble updating an older Ember app.

I've ported the code into a new, empty ember app and installed the dependencies. I get no error when I serve the app, but when I inspect the browser console, I see that the app failed to launch.

Uncaught Error: Could not find module `ember/load-initializers` imported from `<my-app>/app`

I've seen a similar SO post that suggested this was caused by issues with ember-cli and jquery. link

However, that post is over a year old and I'm running an up-to-date version of ember along with an newer jquery library. Sure, it's no guarantee, but it seems a bit unlikely that this is still an issue for ember-cli.

My app/app.coffee file is pretty basic (no additions)

`import Ember from 'ember'`

`import Resolver from 'ember/resolver'`

`import loadInitializers from 'ember/load-initializers'`

`import config from './config/environment'`

Ember.MODEL_FACTORY_INJECTIONS = true

App = Ember.Application.extend
  modulePrefix: config.modulePrefix
  podModulePrefix: config.podModulePrefix
  Resolver: Resolver


loadInitializers(App, config.modulePrefix)

`export default App`

From the console, I can verify that my app is using the expected jquery version: $ Ember.$.fn.jquery "3.2.0"

However, from the command line, I get a different version. $ bower jquery -v 1.8.0 I'm not sure whether that's meaningful or a red herring.

At any rate, my ember-cli is fairly recent. ember-cli: 2.12.0

I've added links to the package.json and bower.json files, in case they contain any clues.

At this point, I'm not really sure how to troubleshoot the issue. The depency




Adding another Ember application as a dependency

I have been tasked with adding admin functionality to an existing Ember application. I am trying to determine how best to break up, what could end up being, a very large Ember application.

The administration functionality is going to be feature rich and am keen to avoid standard users having to download all of the unnecessary admin code. The important consideration for the admin functionality is that it will need to include almost all of the routes that the existing application has.

I'm trying to work out how I can go about neatly breaking up the two codebases. Currently the best I have is to convert my existing application into an addon that can still be deployed separately.

To ensure I don't regret this decision in few years, can anyone suggest any better approaches to this?




Ember Sign-up CreateUser not a function

I am trying to create a user on ember with Firebase for the backend. Here is my code on my sign-up controller:

import Ember from 'ember';

export default Ember.Controller.extend({  
  firebase: Ember.inject.service(),
  actions: {
    signUp() {
        let controller = this;
        var email = this.get('email');
        var password = this.get('password');
        this.get('firebase').createUserWithEmailAndPassword(email, password).catch(function(error) {
            var errorCode = error.code;
            console.log(errorCode);
            var errorMessage = error.message;
            console.log(errorMessage);
        });
    }
  }
});

currently getting the error that createUserWithEmailAndPassword is not a functionHere is a screenshot of the error Thank you.




Ember-Power-Select: Check if somethin is selected?

how can I check in Ember if ember-power-select has a value/something is selected?




Ember.js empty model from REST api

I try to make a list from REST api datas.

The server give me a response like this:

{
    "data" : [
        {
          "playId" : "624a6a21-d2b4-40c4-a241-0d9660a17676",
          "title" : "Hamlet",
          "seats" : 250,
          "reservableSeats" : 200,
          "location" : "The Dysk",
          "time" : "2017-08-02T22:10:00.000+01:00",
          "readOnly" : false,
          "isCanceled" : false

        {
          "playId" : "624a6a21-d2b4-40c4-a241-0d9660a17677",
          "title" : "Hamlet2",
          "seats" : 250,
          "reservableSeats" : 180,
          "location" : "The Dysk",
          "time" : "2017-08-03T22:10:00.000+01:00",
          "readOnly" : false,
          "isCanceled" : false
        }
    ],
    "prevPage" : "http://ift.tt/2mZVF0N",
    "nextPage" : "http://ift.tt/2ndCxih",
    "objectCount" : 2
}

I have an adapter: app/adapters/application.js

import Ember from 'ember';
import DS from 'ember-data';
import JSONAPIAdapter from 'ember-data/adapters/json-api';

export default DS.JSONAPIAdapter.extend({
  namespace: 'admin/v1',
  host: `http://ift.tt/2n05KLk`,

  authManager: Ember.inject.service(),

  headers: Ember.computed('authManager.accessToken', function() {
    return {
      "X-Auth-Token": `${this.get("authManager.accessToken")}`
    };
  })
});

I want to use this model: app/models/demoplays.js

import DS from 'ember-data';

export default DS.Model.extend({
  playId: DS.attr('string'),
  title: DS.attr('string'),
  seats: DS.attr('number'),
  reservableSeats: DS.attr('number'),
  location: DS.attr('string'),
  time: DS.attr('date'),
  readOnly: DS.attr('boolean'),
  isCanceled: DS.attr('boolean')
});

I tried few serializers like RESTSerializer in app/serializers/application.js or app/serializers/demoplay.js but my models still empty.

After XHR finished loading i get two warning like this: WARNING: Encountered "objectCount" in payload, but no model was found for model name "object-count" (resolved model name using sorszamgep@serializer:demoplays:.modelNameFromPayloadKey("objectCount")).

Why my models empty?




Ember optional query params

I need to use optional query parameters and despite following previous posts I'm struggling to get it working.

My app is for posting teaching sessions. The setup is:

  • A user can post a teaching session. They can also request a teaching session.
  • If they post a session I use the sessions.new route. In this route the model object returns a new session object with default settings.
  • If they respond to a teaching request I want to pass the teaching request ID to the sessions.new route so that I can pre-populate the model with information from the request, and link the session to the request
  • This is complicated by the fact that I use a multiple page 'wizard' for session creation, so the sessions.new route actually has multiple sub-routes (sessions.new.wizard1, sessions.new.wizard2 etc.)

My current setup looks like this:

Router:

this.route('sessions', function(){
    this.route('new', function(){
        this.route('wizard1');
        this.route('wizard1');
        this.route('wizard3');
        this.route('from-request', {path: 'from-request/:request_id'});
    })
})

The model is defined on the sessions.new route and is shared between sub-routes.

I want to do something like this in the from-request sub-route:

afterModel: function(model, transition){
    this.store.findRecord('request', transition.queryParams.request_id).then(function(request){
        model.set('info', request.get('info'));
    });
    this.transitionTo('sessions.new.wizard1');
} 

This doesn't seem to work at all. I can't access the queryParams on the transition object as I would expect to. Furthermore anything I set on the model does not seem to persist after the transition.

Is there a better way to do this? Am I missing something?

Many thanks




Can't use related model in template (EmberJS)

That's what I have.
2 models: 'Note' and 'User'. Note has field called "user" that makes replation "1 user to many notes". The data is taken from Mirage.

Note model:

export default DS.Model.extend({
    subject: DS.attr(),
    message: DS.attr(),
    user: DS.belongsTo('user'),
    created_at: DS.attr(),
    updated_at: DS.attr(),
});

User model:

export default DS.Model.extend({
    username: DS.attr(),
    email: DS.attr(),
    notes: DS.hasMany('note'),
});

Mirage code:

let notes = [
    {
        id: 1,
        type: 'note',
        attributes: {
            subject: 'Test 1',
            message: 'tttttttttttttttttttttttt',
            user_id: 1,
            'created-at': '2017-03-10 15:04:22',
            'updated-at': '2017-03-10 15:04:22',
        }
    },
    {
        id: 2,
        type: 'note',
        attributes: {
            subject: 'Test 2',
            message: 'klakljadlfkjhasdflij',
            user_id: 1,
            'created-at': '2017-02-10 15:04:22',
            'updated-at': '2017-02-10 15:04:22',
        }
    }
];

let users = [
    {
        id: 1,
        type: 'user',
        attributes: {
            username: 'user',
            email: 'user@email.com',
        }
    }
];

this.get('/notes/:id', function (db, request) {
    let note = notes.find((note) => parseInt(request.params.id) === note.id);
    let result = {
        data: note
    };
    if (request.queryParams.include === 'user') {
        result.included = [users.find((user) => parseInt(note.attributes.user_id) === user.id)];
    }
    return result;
});

The user model is retrieved (as I can see at EmberInspector).
There is empty output when I use inside template.
And there is an empty 'user' model when I use .

I think the issue may be related to the fact that the 'Note' model is retrieved a bit earlier without 'User' model when I'm building a list of notes.

Great thanks for help!




how to reload hasMany relationship data in ember data 2.8

when first time calling model.get('list') its fetching record from server but second time its fetching from store but i want always response from server.

I am using

Ember js 2.8.3

Ember data 2.8.1

my model is like below

model:function()
{   
    var model = this.modelFor('view').get('list');
    if(model.get('content.isLoaded'))
    {
        return model.reload();
    }
    return model;
}

same model was working as i mention above in ember data 1.13.8

Thanks in advance for help.




dimanche 19 mars 2017

Ember FastBoot SimpleDOM body is empty

I'm trying to read from the DOM in an instance initializer in the FastBoot environment but document.body seems to be empty. The following code works in the browser but returns nothing in FastBoot:

const ELEMENT_NODE_TYPE = 1;

// TODO(maros): Get this working with FastBoot. For some reason the SimpleDOM
// body is empty.
const findBootstrapData = (document) => {
  for (let currentNode = document.body.firstChild; currentNode; currentNode = currentNode.nextSibling) {
    if (currentNode.nodeType !== ELEMENT_NODE_TYPE) {
      continue;
    }

    if (currentNode.getAttribute('class') === 'bootstrap-data') {
      return JSON.parse(currentNode.firstChild.nodeValue);
    }
  }
};

export function initialize(appInstance) {
  const store = appInstance.lookup('service:store');
  const document = appInstance.lookup('service:-document');

  const data = findBootstrapData(document);
  if (data) {
    store.push({ data: data.posts });
  }
}

export default {
  name: 'blog-posts',
  initialize
};

The data that I'm trying to read has been injected into the section using an Ember CLI addon. This works perfectly without FastBoot.

How can I get this instance initializer working in FastBoot?




Ember - Get dynamic input value of element in component in test

So I have a simple component which looks like this:

<div class="my-div"></div>
<input class="my-input" type="text" value="" />

And I have two tests like this:

test('get text from div', function(assert) {

  this.set('value', 'my test value');
  this.render(hbs``);

  assert.equal(this.$('.my-div').text(), 'my test value');

});

test('get value from input', function(assert) {

  this.set('value', 'my test value');
  this.render(hbs``);

  assert.equal(this.$('.my-input').attr('value'), 'my test value');

});

The first test passes, but the second one fails. this.$('.my-input').attr('value') appears to be undefined. Why? How can I make this test pass?




samedi 18 mars 2017

How to rerender a component when it contains a helper?

The problem

I'm trying to rerender a component after an action, but the part of the template i need to rerender is not updated, because it comes from the result of a helper i made, or at least i think it's because of that.

In my component template, i have something like this :



In the component js file associated, i have this action :

fillGrid(location, length) {
  /* logic */

  this.rerender();
},

How i did

I found a way to do it but it felt weird, i'm using a booelan that i toggle between true and false in the action to force rerender

fillGrid(location, length) {
    let me = this;
    this.set('show', false);

    /* logic */

    Ember.run.later(function() {
      me.set('show', true);
      me.rerender();
    }, 10);
}

And in the template :


    


Is it the right way to do it ?




Ember 2.11, Data passed between parent to child components.

I have a parent and a child components such that child component have few radio button options which appears based on a checkbox( defined in parent component). I pass the checkbox as a mutable variable to child component. The groupValue of the radio button changes based on the computed property dependent on checkbox in the child component. Now to my surprise, when the init() method of a child component is called, the computed property is trigged. If I change the value of the radio button and change my checkbox, the computed property is not trigged.

So my question is once a mut data is passed from parent to child component, can't a parent changing that data wouldn't trigger child component computed property?




Ember server does not serve dummy app while creating an addon

I am trying to write an Ember component addon. After complete the template structure I think it would be nice to see the layout inside the dummy application as a sanity test.

Follow the instruction below,

The Ember CLI uses a dummy app in tests/dummy for testing. In tests/dummy/app/templates/application.hbs you can put calls to both the helper and component. Then, with ember serve, you can navigate to localhost:4200 to ensure that everything is working as expected.

http://ift.tt/1SwG9E3

However when I use ember s it seems run the addon's app folder instead of tests/dummy. What should I do?




vendredi 17 mars 2017

CrystalReports equivalent for EmberJS

I'm building an application in EmberJS and one of the features ahead is to display in the web app a preview of an invoice and later on to print it.

On previous projects, .NET based, I've used CrystalReports and the experience was very positive.

However, for the current project, in EmberJS, I cannot seem to find an equivalent of CrystalReports. Does anyone have some insight on reporting in EmberJS?

Thanks in advance.




Adapter used with embedded links in Ember

I've been scratching my head on this issue with my ember-data (v2.10.0) adapter not working in the way I expect. I have a model called called say.. posts. The post model is using the default RESTSerializer and has a links attribute in its payload that defines a comments relationship (a has-many relationship between posts and comments). The comments resource is loaded asynchronously at a nested path under posts at api/posts/:post_id/comments on the server. My question is, where does the ember-data adapter for comments live? I have attempted creating a top-level comment adapter, but that seems to do nothing. Am I missing something? Thanks in advance.




How can you manipulate db content thats returned from findAll function in model hook of ember?

The return value of findAll is an unknown mixin. eg . in router xyz.js

model(){
a = this.store.findAll('food-track');
return a
}

How do we manipulate a or extract data from a in model itself like

model(){
a = this.store.findAll('food-track');
some_data = a['_id'];
some_more_data = a['name'];
return some_more_data
}

But then a isn't in a format that I expected it to be in and I wasn't able to perform any function like this? Btw the data is taken from couch/pouchdb.




store.CreateRecord push record to store even negative response from server

I have following function:

    this.store.createRecord('user', params).save().then(()=>{
      this.set('responseModal', 'Utworzono użytkownika!');
    })

And my question is: Why Ember push record to store before response from server? For example: I'm filling form incorrectly, and my server return with error and status: 400, but my record without it's id-key is still in store. I tried something like this:

.catch(()=>{
      user.unloadRecord();
    });

But it looks bad, when something record display and instantly hide. Is something way to create record in store only after response from server without external libraries? I want to use only ember-data to connect client with the server. Any advice and suggestions will be appreciated




PhantomJS has crashed - Fatal Windows exception, code 0xc0000005

We have built a application using EmberJS. We got a failure message when we test the application using ember test. Here I mentioned the error message

OS: Windows 8(64-bit) PhantomJS: 2.1.1

PhantomJS - error
    ---
        message: >
            Error:          
            Non-zero exit code: 3221225477
            Stderr:
             Fatal Windows exception, code 0xc0000005.
            PhantomJS has crashed. Please read the bug reporting guide at
            <http://ift.tt/1TxnIQg; and file a bug report.


        Log: |
            { type: 'error', text: 'Error: Browser exited unexpectedly' }
            { type: 'error', text: 'Non-zero exit code: 3221225477' }
            { type: 'error',
              text: 'Fatal Windows exception, code 0xc0000005.\r\nPhantomJS has crashed. Please read the bug reporting guide at\r\n<http://ift.tt/1TxnIQg; and file a bug report.\r\n'
 }




How to send data from route to component?

I am beginner to ember.

I want to send data from route to component.

import Ember from 'ember';
var model = null;
export default Ember.Route.extend({
    model() {
        return true;
    }
});

i have defined this model in route now i want to use this model in component js file. i have just do console log but it gives undefined. my component js code is below

import Ember from 'ember';
export default Ember.Component.extend({
    didInsertElement() {
        console.log(model);
    }
});

So can anyone suggest what is the actual way to use data of route in component.




ember acceptance test for mouse draggable actions

As we have ember helpers for all events, how can i cover my drag and drop events in the components through acceptance test ? Provide a test with some working example.




What is a proper way to handle temporary record states in Ember JS?

Let's say I have a list of records that are supposed to have state selected in some current context. I can see two approaches here:

  1. Create an array of objects: records.map(record => { record: record, selected: false }), get and set like `recordObj.set('selected', true). Render this array.

  2. Set property explicitly on record objects: record.set('selected', true). Render RecordArray.

The second one looks much easier than the first as you don't have to manage additional array and objects (this becomes a real hassle).

The problem is that if you set anything on a record object, even a field that is not present in the model, it will still persist through the application (I guess until the model is reloaded and new record object is created?).

How to prevent that and ensure that temporary properties will be clean on every route change? Or how to improve the first approach? Is there anything I'm missing?




jeudi 16 mars 2017

Returning a hyperlink in an Ember component

I have an Ember component called alert-message which returns a more user-friendly error message for validation purposes. One of the error messages contains an ID (which I've hardcoded here)- I'd like to turn the ID into a hyperlink and display it in the message.

I understand using the str.link() method simply creates a string representing the code for an HTML link element.

What I currently have renders this: "Cannot update this item with <a href="/items/31010-2001-20311">31010-2001-20311</a>."

How do I turn the generated html into an actual link?

In my component template I render:

import Ember from 'ember';
    export default Ember.Component.extend({
      errorMessage: function () {
        const status = this.getWithDefault('status', '');
          if (status === '409') {
            var id = 31010-2001-20311;
            var idLink = id.link('/items/31010-2001-20311');
            return `Cannot update this item with ${idLink}.`;
            }
        {
          return status;
        }
      }.property('status')
    });




Filtering Firebase JSON Data on EmberJs

How would I go about receiving multiple records from a firebase DB with Ember JS as the user is typing in a search box? When pushing data firebase generates an automatic ID for the JSON which is required for searching the data by individual records. This is how the firebase DB looks likeenter image description here

I would like it to search and return both of the entries as the user is typing "San" in the search box. Thank you.




Is it right to try moving my front end packages from bower to npm?

I am quite new to ember and was trying to build a small to-do list app when I started facing a problem wherein I tried installing moment package through bower install moment but somehow importing the package into ember-cli-build.js didn't work out. I came across a solution that said I should runnpm install moment over it and that worked for me. Following above events I tried removing the moment package from bower_components and changing the path to node_modules. This didn't work out though and broke my app instead. I was getting the following error:

The Broccoli Plugin: [SourceMapConcat: Concat: Vendor /assets/vendor.js] failed with: 

Error: ENOENT: no such file or directory, open '/Users/kshitij/scratch/ember-projects/em-app/tmp/source_map_concat-input_base_path-http://ift.tt/2n3kVFt  

My question: Is trying moving bower packages to npm correct? If yes, then why it doesn't work out in this case?

Note: I could also have solved the problem by adding "moment" to "predef" block of .jshint.rc file in the application directory but I want to know why the npm method worked out and why porting the moment package entirely from bower to npm doesn't work.




Ember JS automatically register directory classes to DI

Creating in-repo-addon in Ember.JS gives a lot of possibilities. Today I've stumbled into a case when I wanted to register all classes in directory (for example my-dir) into Dependency Injector (same way it's done with services by Ember, but I wanted to use some other namespace).

For example I want to allow developer to create multiple classes inside proxy directory, and register all of them in DI under proxy: namespace. So later we can use:

Ember.Component.extend({
  myProxy: Ember.inject('proxy:my'),
});




Ember include external JS via external HTTP server

I would like to include this library (Bootbox) . It does have a an npm package, but I would like to include it via its CDN (public url).

What is the right way to include external javascript (and css) files which reside on publicly accessible servers?




Ember Data relationships not resolved

I'm still learning ember.js and have run into a roadblock with ember data not resolving lookup relationships in models. I have one model 'site' that will be basically a lookup table for every other model to differentiate data based on location.

At this point, I'm doing something wrong or missing a key concept - probably both... (or maybe it's the wee hour!)

Site Model (i.e. the lookup table)

import DS from 'ember-data';

export default DS.Model.extend({
    code: DS.attr(),
    name: DS.attr(),
});

The site model would have a hasMany relationship to all my other models (will be about 12 when complete)

Associate Model

import DS from 'ember-data';
import { belongsTo } from 'ember-data/relationships';

export default DS.Model.extend({
    site: belongsTo('site'),
    last: DS.attr(),
    first: DS.attr(),
    active: DS.attr('boolean'),

fullName: Ember.computed('first', 'last', function() {
  return `${this.get('first')} ${this.get('last')}`;
  }),
});

The 'associate model' will also be a lookup along with 'site' in some other models.

I'm providing data via the JSON API spec but I'm not including the relationship data because as I understand it, ember data it should be pulling down the site data using the site id attribute.

{
    "links": {
        "self": "/maint/associates"
    },
    "data": [
        {
            "type": "associate",
            "id": "1",
            "attributes": {
                "site": "6",
                "last": "Yoder",
                "first": "Steven",
                "active": "1"
            },
            "links": {
                "self": "/associates/1"
            }
        }
    ]
}

In my template file I'm referencing associate.site which gives me an error.

<(unknown mixin):ember431>

If I use associate.code or .name to match the site model, nothing will show in the template. The code from the 'site' table is the data I really want to displayed in the template.

So the obvious questions:

  1. Am I wrong that Ember Data should be resolving this or do I need to include the relationship in my API response?

  2. I realize that my belongsTo in the 'associate' model only references site while I want site.code, so how do I make that relationship known or access the field in my 'associate' model?

  3. I didn't include hasMany relationship in the 'site' model because there would be many. Do I need to do an inverse relationship in other models? Examples I've seen don't all show the hasMany relationships setup.

  4. When I look at the models in ember inspector the site field is not included in the model. Even if I wasn't getting the correct data should it still show up?

I like ember so far, just need to understand and get over this roadblock




Ember - observer in previous route fires when property set in didTransition hook of next route

In my index route, I have an observer that fires an action when the user object is set in the session service, as shown below. This works fine- the console logs 'index route observer fired' and the action fires.

routes/index

session: Ember.inject.service(),
  sendTheAction: function() {
    console.log('index route observer fired');
    this.send('checkLicense');
  }.observes('session.user'),

  actions: {
    checkLicense: function() {
      if (this.get('session.user.email)) {
          //get the user's email and send off an AJAX request.
        }
      },
    }

I also have a logout route which (among other things) sets session.user to an empty object, and then transitions to the login route. I simply use a link-to helper pointing to 'logout' to initiate this.

routes/logout

session: Ember.inject.service(),
  actions: {
    didTransition: function() {
      this.set('session.user', {});
      this.transitionTo('login');
    }
  }

If I am in the index route and I click logout, the transition to logout begins. Then, when session.user is set to {} in the logout route's didTransition hook, the observer in the index route fires. The console logs 'index route observer fired' but then I get a console error saying

Error while processing route: logout Nothing handled the action 'checkLicense'.

I'm not sure how the observer in the previous route can still be fired by a change in the logout route's didTransition hook, as I thought didTransition only fired when the transition was fully resolved.

I think that it is then looking for the action "checkLicense" in the logout route.

Can anyone clarify why that observer still fires, and how to get around this?




mercredi 15 mars 2017

How to use a handlebar template?

I bought a theme expecting it to have HTML and Angular versions but all I see are HBS files. I am newbie to the grunt/express/npm the whole scenario and I'm lost on how to extract a possible html version from these files.

There is a Gruntfile.js and I tried running "grunt" on CLI but I get an error saying "unable to find local grunt file". Feels like it is some sort of Handlebar template.

Below is the file structure. enter image description here

enter image description here

If this is the wrong stack site, instead of down voting please mention the proper one. I will post it there. Thank you in advance.




How do I use ember-crumbly for non-nested routes?

I'm trying add breadcrumbs to this application using ember-crumbly.

I couldn't find the git repo, so to see the code, you'll have to clone the full application by clicking the button "Download git repository" in Course Material and then go to the branch step-14 by running the following command after going into the repo via command line:

git checkout step-14

I'm adding breadcrumbs by making the following changes to the files:

app/routes/album.js

import Ember from 'ember';

export default Ember.Route.extend({
  breadCrumb: {
    title: 'Album'
  }
});

app/routes/index.js

import Ember from 'ember';

export default Ember.Route.extend({
  breadCrumb: {
    title: 'Home'
  },
  model() {
    return this.store.findAll('album');
  }
});

app/templates/application.hbs

<header>
  <h1>BümBöx</h1>
</header>

<div class="breadcrumb">
  
</div>





I'm hoping when I go to http://localhost:4200/album/1, it would look like this: enter image description here

but instead, it looks like this: enter image description here

I'm guessing it's because my routes are not nested in directories (as in it's not app/routes/home/album.js), which isn't compatible with the demo from ember-crumbly. Can someone help me figure out how to add ember-crumbly to this application? Much appreciate.