samedi 30 septembre 2017

Ember error about ActiveModelAdapter.extend

I am learning ember and rails from this tutorial http://ift.tt/1MJXarA

I understand this is a pretty old tutorial and some code does not apply anymore. I am able to fix most of the error during learning process. However, there is one error I have no idea how to fix.

I have this piece of code:

import DS from 'ember-data';

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

And I got this error:

Cannot read property 'extend' of undefined@ 187 ms
Expected:   
true
Result:     
false
Source:     
TypeError: Cannot read property 'extend' of undefined
    at Module.callback (http://localhost:4200/assets/popular-media-app.js:11:59)
    at Module.exports (http://localhost:4200/assets/vendor.js:111:32)
    at requireModule (http://localhost:4200/assets/vendor.js:32:18)
    at Class._extractDefaultExport (http://localhost:4200/assets/vendor.js:70638:20)
    at Class.resolveOther (http://localhost:4200/assets/vendor.js:70359:32)
    at Class.superWrapper [as resolveOther] (http://localhost:4200/assets/vendor.js:56118:22)
    at Class.resolve (http://localhost:4200/assets/vendor.js:23536:35)
    at resolve (http://localhost:4200/assets/vendor.js:21501:36)
    at Registry.resolve (http://localhost:4200/assets/vendor.js:21189:21)
    at Registry.resolve (http://localhost:4200/assets/vendor.js:21193:55)

After tons of testing, I am sure the problem is cause by ActiveModelAdapter. I went through the documents for this class. It seems fine. I really have no idea why this is an error. Could someone help me with this?

I understand you may not be able to figure out what's wrong with the code I provide, but I really don't know what other code do you need. If you need additional code, please let me know.




vendredi 29 septembre 2017

ember normalizeResponse when navigated to page vs link_to

When I navigate to a specific page, the overridden function normalizeResponse in my serializer used in conjunction with code in my router model function, to add meta data to my model, works correctly. Basically, normalizeResponse runs first, then my model function in my router.

serializers/application.js

import App from '../app';
import JSONAPISerializer from 'ember-data/serializers/json-api';

App.storeMeta = {};

export default JSONAPISerializer.extend({
  normalizeResponse(store, primaryModelClass, payload){
    App.storeMeta[primaryModelClass.modelName] = payload.meta;
    return this._super(...arguments);
  }
});

And in my model.

 model(params){
    const data = {};

    return this.store.findRecord('myModelType', params.id).then((myModelType)=>{
      myModelType.meta = App.storeMeta['myModelType'];
      return myModelType;
    },()=>{ //error
      this.get('session').invalidate();
    });
  }

When I navigate to that specific page through a link_to from another page, the model code gets called first, so there is no meta data being attached to the model.

How do I get the normalizeResponse function to run before the model function when navigated to from link_to?

Any help would greatly be appreciated.




what's the absolute path to refer files in ember-cli tests/?

Like I can include any file in app/ with import Something from '<app_name>/...', what's the corresponding thing for files in tests/?

Now I always use relative path but sometimes it's quite annoying.




Ember component integration test: inFlight error on model save

I am trying to test a component handling newsletter-subscriptions. I want to test whether the submitForm function saved successfully by setting a class of a hidden input accordingly after the save happened or did not happend so that I can assert this in an integration test.

Here is my code:

newsletter.subscription.js:

import Ember from 'ember';

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

  didInsertElement() {
    this.set('model', this.get('store').createRecord('subscription'));
  },
  actions: {
    submitForm() {
      this.get('model').save().then(
        (json) => {
          this.get('displayNotifications').success({
            key: 'subscription.success',
          });
          this.set('model', this.get('store').createRecord('subscription'));
          this.set('subscribed', true);
        },
        (reason) => {
          this.set('subscribed', 'error');
        });
     }
   }
});

Here is the code of the newsletter-subscription.hbs:

<div class="ui container row newsletter-form">
  <div class="ui inverted segment">
    <form class="ui form" >
      <div class="ui stackable grid">
        <div class="eleven wide right aligned column">
          
        </div>
        <div class="five wide inverted left aligned column">
          <button type="submit" class="ui fluid secondary button ">
            
          </button>
        </div>
        <input type='hidden' id="debug" class="" />
      </div>
    </form>
  </div>
</div>

And here is my test: newsletter-subscription-test.js

 moduleForComponent('newsletter-subscription', 'Integration | Component | newsletter-subscription', {
   integration: true
 });


 test('newsletter-subscription: submitting newsletter-subscription sets subscribed to true', function(assert){

    this.render(hbs``);

    assert.equal(this.$('#debug').hasClass("notSubscribed"), true, 'before click, debug element has class notSubscribed');

    this.$('input[name=subscription-email]').val("test@example.com");
    this.$('button[type=submit]').click();

    return wait().then( () => {
      assert.equal(this.$('#debug').hasClass("subscribed"), true, "after callback of click ran, debug element has class subscribed");
    });

 });

The first assertion works. But then I keep getting an error:

✘ Assertion Failed: You can only unload a record which is not inFlight.

From breakpoint analysis, I found that this happens when this.get('model').save() is called. My tries to resolve the issue remained ineffective so far (i.e. mocking server response using mirage). Is there an issue with the Ember run loop in this context that I somehow have to take care of or something different?

Thank you for your input!




How to use an Ember.getOwner(this).lookup('application:main') result

As the title say, I have some problem understanding what does this call return.
This is how I am using it:

fetchEngines()
    {
        let object = Ember.getOwner(this).lookup('application:main').engines;
        console.log(object);
    }

And it return me something like that: example

At this point, this is what I want, the list of all my ember-engines.
But I don't know how to use it. By that I mean, how do I fetch the name of each engine, what is object at this point, I can't find anything about it.

I have tried the forEach() method, but it returns me : object.forEach is not a function. I have also tried the Object.keys method, but it returned me undefined, maybe somebody can indicate me a doc or something, I don't understand at all what is it.
Good day to you and thank you for reading.




jeudi 28 septembre 2017

How to add to an ember blueprint's renamedFiles property?

An ember blueprint has a static property called renamedFiles that by default renames gitignore from the files folder to .gitignore in the target folder.

The question is, how can I extend this list?

So far I tried these in the index.js of my blueprint, but they don't seem to work:

module.exports = {

  renamedFiles: {
    'something': 'somethingElse'
  },

  beforeInstall: function() {
    this._super.renamedFiles = {
      'something': 'somethingElse',
    };
  }
};




Change CSS when model changes or DOM value changes in ember

I have a table and it gets the data from DS model which dynamically updates from the database. I need alert of color (css) change of the block( particular “td”) in UI when the data updates in the table.

Here is my code:

 <table class="table table-bordered table-hover">
    <thead>
           <tr>
                <th>C</th>
                <th>Flight</th>
           </tr>
    </thead>
    <tbody>
    
    <tr>
            <td></td>
            <td></td>

    </tr>
    
    </tbody>
    </table>

I need the color of the block “flight” change when the value updates.




Change route outside Ember app

I'm having a problem with changing route outside Ember app. Code of the app is external and it's not possible to extend it in any ways. What I tried so far:

  1. Changing location.href (Ember unable to catch this event and full page reload occurs)
  2. Using History.pushState() (doesn't change anything)
  3. Changing href attribute on existed link (Ember remembers initial value and ignores new one)
  4. Thinking about compiling template with helper, but Ember.View isn't globally available. And I don't know routes, however it's not a problem – I need it on one particular service and routes can be reverse engineered.

Maybe there is more elegant way to do it?




Migrate Ember app from bower to npm

As I understand Ember Team recommended to migrate applications from bower to npm, but I wasn't able to find clear migration plan for that. Does someone have successful migration experience? Could you please share your experience or give some useful links with detailed instructions. Thanks.




How to open the dropdown of Ember Power Select from outside?

As the title says, we would like to open the dropdown of the Ember Power Select (http://ift.tt/25XClF1) from outside, i.e., from a parent component or the route's template.

As far as we have checked, there is no way to trigger the action open of the component, which btw wouldn't be correct in the sense of "data down, actions up" principle. So, rather we need to "register" some data attribute that allows us to trigger to open the dropdown by altering the data attribute.

But maybe we have overseen something and somebody could propose a solution to our requirement to open the dropdown from outside?

Example: Ember Power Select is part of a bigger component, e.g., some bigger div. When the user clicks wherever on that div, the dropdown opens.

Thanks for any input!




Choose between different style for an Ember.JS application

The issue I have is that I can't find a way to 'change' the css style within my application.

The thing that I want to access is for example: I have a red theme, but I want that the user can choose an other predefined theme, like a green, or a blue theme.
The idea is that I have different app.css, how can I change between one another, I can't find method to do so. Maybe I can do it in my environnement.js?
Any tips is apreciated.
tl;dr: How to set multiple css style in our Ember.JS app?




How can I write custom handlebars in Ember js?

js:

Ember.Handlebars.registerHelper('demo-helper', function (property, options) {
    console.log('demo helper');
    return '<li><a> '+ msg+'</a></li>';
});

hbs :

msg

How can I wrap hi (inner html of handlebar) with any custom tag?.I know that component has tag parameter that encapsulates html with given tag. But it supports only one tag. I want to encapsulate with multiple tags like

<li><a>innerhtml</a></li>




Send action to 'parent' component from child component

i wanted to ask, if sending action from component that is used inside another components template is possible.

So we have component1 used on /new page:



And in it's template i'm using



And in Component2 template i have:

<button action="add">

So now i want to send "add" action through component2's controller into component1's controller.

As far as i know sendAction() will ignore component1 and will go straight to controller. I also tried using targetObject on component2 but i think it's deprecated.

Is it possible without any hacks?




Not possible to use shorthand route handlers if RestSerializer is used? (ember-cli-mirage)

I set up a simple Ember Twiddle to show you my error that is occurring when trying to update a model. It's considerable that I'm using ember-cli-mirage for mocking the data. According to the docs, I created a shorthand route that should handle the PUT request. It does, but with the error: Your handler for the url /api/shops/1 threw an error: Cannot convert undefined or null to object

When using the JSONAPISerializer, everything is working with shorthands (mirage/config.js) and I'm able to update models, but in my case I have to use the RESTSerializer with serialized IDs in the responses. The request payload when I'm sending the model's attrs are without Id at the end of the property name, f.e.:

// attrs object in PUT request { name: "Shop 1", city: "1" // belongsTo relationship, }

Now Mirage is trying to find those properties on the respective database model that has to be updated, but cannot find it, because in the database it's cityId and not just city...

I also found this issue report and it’s working, but I was hoping I could avoid something like this. As far as I can remember, in previous versions of ember-cli-mirage (v0.1.x) it was also not needed to override the normalize method in the serializer to be able to make use of the RestSerializer with serializedIds…

My question is: Is there a way to stick to shorthand route handlers only, or do I really have to write a helper or other custom solution only because I have to use the RestSerializer? That would be really sad, but at least I would know then.

Thanks for your support!




How to always load an ember-engines with Ember.JS

I am currently trying to access my ember-engines wherever I am. I want to have the name of each engines, because I want to display every engines in my main application.
The problem here is that I can't find a way to catch there name, because the engines are loaded only if we navigate to a page related to the engines.
This is the services that is normally catching every name of each engines, call it engines-manager:

import Ember from 'ember';
import App from '../app';

/**
 * This service will help us manage every engines that are in our application,
 */

export default Ember.Service.extend({
    availableEngines: [],

    addEngines(engines)
    {
        this.get('availableEngines').push(engines);
        console.log(this.get('availableEngines'));
    }
});

And then in every engine, more precisely, in every anEngines/addon/engine.js of every engine, I put :

import Engine from 'ember-engines/engine';
import loadInitializers from 'ember-load-initializers';
import Resolver from './resolver';
import config from './config/environment';
import Ember from 'ember';

const { modulePrefix } = config;

const Eng = Engine.extend({
    modulePrefix,
    Resolver,
    dependencies: {
        services: [
            'engines-manager'
        ]
    },
    enginesManager: Ember.inject.service('engines-manager'),
    init() {
        this._super(...arguments);
        this.get('enginesManager').addEngines('nameOfMyEngines');
    }
});

loadInitializers(Eng, modulePrefix);

export default Eng;

This method is working if we go on the engines related page, but I dont want to go to every page to load them, so here is my question: how to always load an ember-engines?

PS: setting my lazy-loading to trueor false doesn't change anything.




mercredi 27 septembre 2017

How can I model singletons without an id in ember?

I am new to ember and am trying to migrate an existing application, and would like to know what the recommendation is for modeling a single object that will be reused in multiple components on every page. ie: As part of the initial load, I would like to perform a GET request against a URL like 'http://ift.tt/2wkjoNb' and get an object back like:

  {
    name: "Users Name"
    email: "user@email.com",
    profileImg: "http://ift.tt/2fB0ONE"
    ... snip ...
  }

This object will then be used in components for menus, toolbars, and a form for updating it via a post to the same URL.

What is the best way to model this workflow in ember? Given that this is an incidental object and not the focus of most routes, it does not seem to make sense to specify it as the model of them. Also, does ember data handle cases where a model is a singleton and does not have an ID, or would I need to use something like Ember.$.ajax ?




Ember.js : Modify request URL

I create an Ember app with a Symfony REST api. I also use the REST adapter for my requests.

I have 2 models in my app : users and their related comments. I already created CRUD operations for my user properties and now I focus on the CRUD operations for comments.

Model user.js

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

    comments: DS.hasMany('comment')
});

Model comment.js

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

    contact: DS.belongsTo('contact')
});

I have a route which shows all comments (and other data) of a given user. The request loads the user object and his relations. On the view I also have a form and an action to create a new comment for this user.

Route users/get/comments.js

import Ember from 'ember';

export default Ember.Route.extend({
    model(params) {
        return this.modelFor('user.get', params.user_id);
    },
});

Controller users/get/comments.js

import Ember from 'ember';

export default Ember.Controller.extend({

    newComment: null,
    user: null,

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

        let comment = this.store.createRecord('contact');
        this.set('newComment', comment);
    },

    actions: {
        saveComment: function() {
            let user = this.get('model');
            let comment = this.get('newComment');

            comment.set('user', user);
            comment.save();
        }
    }
});

Everything works, except for the request sent to the backend. I loaded the comments from the user, so I expect a call to :

POST http://ift.tt/2hAqPgU

Instead the call is sent to :

POST http://ift.tt/2fPXc7h

Do you know why and how could I correct it ?

Second problem, the model is loaded from the 'user.get' route. This works because the user comes from this route to this page, but... It's doesn't work if the user enters directly the URL for comments. That sound logical, but I have no clue how to correct this problem... Can you help me ?




How to display a loading screen after form.submit() in ember js

Please consider: - a loading.hbs file exist, which gets called by ember when transaction occurs. - Used form.submit() approach to retrieve data from the server in the Ember framework. I didn't use this.store.findrecord() because we faced some issue in downloading a file (created in the server) as an attachment and so went with the form.submit() approach.

Objective: - a loading screen should get displayed when the form.submit() is triggered until we get the final data from the server.

Problem: - In ember, when we go for this.store.findall() approach, ember automatically search for a file like loading.hbs and it displays the file until the full data is downloaded from the server. - Since we are going via form.submit() approach, the ember is not searching for loading.hbs file to display.

Is there anyway, to display the loading.hbs file when the form.submit() is triggered.

Here is my code:

actions: {
    pdfClick(Id) {
      pdfId=document.getElementById("version_"+Id).value;
      let form = document.getElementById("pdfForm");
      form.action = Globals.urlPrefix + this.get('router.url') + "/" + Id; //This line creates the URL to be triggered
      form.submit();
      form.action = "";
    }
}




Having a link trigger only an action on click, but opening a different route on new tab click

I want to implement the following :

  • First, put a link.
  • When clicked, this link should trigger an action in my current route (i.e. collapsing a panel or something like that)

BUT

  • When user right clicks and selects "new tab", this same link should open a separate route (and also not trigger any action in current route because it wouldn't make sense anyway)

So far I've tried the following:

<span >
  
    Some text
  
</span>

I was hoping to override the default link-to behaviour by enclosing it in a clickable span but to no avail: now when I click on the link text, I am redirected to the new route and the click action itself never happens.

Is it possible to implement something like is using EmberJS or even plain JS tweaks?

Thanks!




Ember-view class attached to div messes up my anchor

So I have an div tag inside an anchor tag (I want to have a clickable div), which div tag has 'ember-view' default class. This seems to mess up with my link and the div cannot be clickable. Even though i tried different ways to have the div as a link (By setting anchor tag z-index for ex.) however div is not clickable. When I take of the class ember-view from div seems to work. Can you help me with this issue ? How do I properly render a div as a link. Browser view of the issue




Cancel Ember Data call

As known in ember when queryrecord.find("modelName") is released a call is made. is there any way to cancel that call like we cancel an ajax call ? ( xhr.abort() )




Accessing Store data in service Ember js

I am trying to peek a store from the service, by injecting the store in my service. The peekRecord function returns a Class. What is the best way to access the record that the store returns?

As peekRecord is synchronous I tried like:

const hasPermission = this.get('store').peekRecord('system/permission','PlatformRead');
console.log(hasPermission.data);

Is there any Ember specific way to access the record that's returned from the store?




mardi 26 septembre 2017

How to re-use an ember route in two different routes?

My router has paths setup for listing wallpapers. The index shows a list of wallpapers. There is also a categorized list of wallpapers. And lastly, there's a page for viewing a specific wallpaper.

The paths are setup like this:

  1. /wallpapers/ list of wallpapers
  2. /wallpapers/:category_id/ list of wallpapers for specific category
  3. /wallpapers/:category_id/:wallpaper_id/ Single wallpaper page

Entries in both 1 and 2 show 3 after a click.

Now I want 3 to be a modal that pops up with the previous route in the background. I can get this to work using either 1 or 2 as parent. But if I want to do this for both, I need to completely duplicate the route, controller, template and model for 3. Any attempt to use the existing controller for both places causes it to work for one route only.

How can I use the same route/controller/template/model combo for the modal to be used in both 1 and 2?

Router.map(function() {
    this.route('wallpapers', function() {
        this.route('index', { path: '/' }, function() {                         // All wallpapers
            this.route('wallpaper', { path: ':category_id/:wallpaper_id' })     // Modal dialog
        })
        this.route('category', { path: ':category_id' }, function() {           // Categorized wallpapers
            this.route('wallpaper', { path: ':wallpaper_id' })                  // Modal dialog
        })
        this.route('wallpaper', { path: ':category_id/:wallpaper_id' })         // Single wallpaper
    })
})




How does a frontend framework speak to a database?

I am learning some frontend and came across emberjs. It seems to be pretty interesting. I saw that emberjs has the ability to speak to elasticsearch directly and this has brought up quite a few questions for me.

  1. How is it possible for a browser application to speak to an elasticsearch cluster? Is it implied that the elasticsearch cluster is exposed as a public interface?

  2. I would think such an implementation would be browser application -> backend framework -> speak to a database. This seems like it is cutting off the need to have a backend framework? Am I incorrect?

  3. Are there reasonable use cases for a frontend framework to be speaking directly to a data store?




How would I write a sendAction helper?

In ember, we have the action helper;

  

But, when I want to send actions to a parent component, I still have to explicitly write an action on the child that calls sendAction. Even if I'm ONLY bubbling an action. I'd like the avoid this with a send-action helper;

  

Does anyone know how I'd implement this helper?




Ember Model Computed Property Not Working

I have a module logging errors on my MEEN stack app. I have a model for my ember route that pulls in data from my express server via mongoose.

I wanted to alter the date property on my model to format the date differently from how it is stored in the mongo database to save some real estate on the page ie: Tue Sep 19 2017 16:57:17 GMT-0400 (EDT) to 2017-09-19.

I followed the Ember docs for computer properties on the model but the template is not displaying the computed value.

model:

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

export default DS.Model.extend({
  error: DS.attr('string'),
  user: DS.attr('string'),
  module: DS.attr('string'),
  date: DS.attr('string'),
  smallDate: Ember.computed('date', function() {
    var dateObj = new Date(this.get('date'));
    return `${dateObj.getFullYear()}-${dateObj.getMonth()}-${dateObj.getDate()}`;
  })
});

template:

<div class="row">
  <div class="col-md-8 col-md-offset-2 text-center">
    <h2 class="toolTitle">Blame Panel</h2>
  </div>
</div>
<div class="col-md-8 col-md-offset-2">
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>User</th>
        <th>Error</th>
        <th>Component</th>
        <th>Date</th>
      </tr>
    </thead>
    <tbody>
      
        <tr>
          <th scope="row"></th>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
      
    </tbody>
  </table>
</div>

If I just use the date property of the model it displays the unformatted date fine.




Ember Blueprint skip confirmation

I use the ember blueprint.Install(options) method to create files based on blueprint, but this causes overwrite questions for existing and not identical files. I allways want to skip that kind of questions, is that possible?

Is it maybe possible to override a public method from blueprint.js somehow?




In Ember JS, all the code simulates CSS commands

When I write "navbar margin-top: 50px" in my CSS, the entirety of my code is moved down 50px, so that my H1 and navbar appear on the same line regardless of what route I choose. Obviously, I want to be able to manipulate different pieces of my code for different pages. New to Ember, please advise.




Ember.js upgrade from version 1 to 2 mandatory?

We have an web application which uses ember.js version 1.11.3. Can we safely stay on this version, or is an upgrade to the latest ember.js version kind of mandatory (for security or maintanability reasons)?




On running Ember Cordova app on phone, Got error - Cannot read property 'notification' of undefined

Installed cordova-plugin-local-notifications and retried it. The line of code where the error occures -

cordova.plugins.notification.local.on("click", function (notification) {

Error:-

Error while processing route: dashboard Cannot read property 'notification' of undefined TypeError: Cannot read property 'notification' of undefined

On commenting that line, I got another error for the immediate next line

states[Connection.UNKNOWN] = 'Unknown connection';

Again giving an error saying connection doesn't exist. I assumed that there's some cordova package or dependency missing. But running this same lines of code on anoher app's application.js, gave no such error. there was nothing related to cordova missing from package and bower json files, when comparing the app that worked, with the one that didn't.

Also in this case, cordova didn't have the function plugin. But the other app that had the same packages and lines of code in application.js, had plugin in cordova object.




lundi 25 septembre 2017

What happens when we enter ember serve?

What happens when the Command ember serve is entered.

When we enter ember serve, ember will serve our project in http://localhost:4200.

what is the process that is behind the screen?

Thanks in advance :)




Ember control does not come back to loop after sending action

In my Ember app, I have the following code to remove checked rows dynamically

removeRow: function(row){
    // Some logic to remove one row at a time
    var numberContainers = this.get('containers').length;
    for (var i = 0; i < numberContainers; i++){
    }
}

this.get('containers').forEach(function(container){
    if (container.applicable === true){
        var row = {};
        self.send("removeRow", row);
    }
})

Now user can select multiple rows & try removing them. With the above code, the "removeRow" action is invoked only once i.e. the forEach loop somehow gets broken or control does not come back again after the "removeRow" action is invoked once.

How can I handle this scenario ?




glimmer.js IE Support

a new untouched glimmerjs app with ember new my-app -b @glimmer/blueprint ran in firefox and chrome but not in ie or edge.

Edge gave me following error:

SCRIPT1028: Expected identifier, string or number: 
app.js (3386,11)

IE11:

SCRIPT1002: Syntaxfehler
app.js (7,1)

After adding IE11 in config/targets.js the app runs with "Microsoft Edge", but still not with IE11.

IE11 provides following error, which referes to a let Symbol:

SCRIPT5009: "Symbol" ist undefiniert
app.js (9804,1)

Any other settings we need to change?

Also it's a little bit strange that with setting IE11 the Edge problem got fixed.

Or that the default setting 'last 2 Edge versions' does not transpile to a edge compatible version...




dimanche 24 septembre 2017

Binding actions to a component helper fails if the component is changed dynamically

In a route lives a slide-out panel that shows a 'quick quote' workflow. This initially shows a default component, but the user can navigate back and forth through a bunch of steps.


    


Which component is displayed is determined by the 'qqComponent' property. The action 'navigateQuickQuotePanel' changes the value of 'qqComponent' based on passed parameters:

navigateQuickQuotePanel(component) {
    set(this, 'qqComponent', component);
},

This works fine initially and when the value of qqComponent changes, a new component is displayed. However, at that point it appears that the 'onNavigate' property, which should be pointing to the 'navigateQuickQuotePanel' action, is actually null (as the action does not seem to have been rebound to the new displayed component).

Any help in this regard would be appreciated, as binding properties in this manner works fine. For example, where I have the below and the displayed component modifies these properties directly, it works fine.


     


Please note the quick quote cannot be done through routes, as the overlay can appear over any route in the website.




How to generate HTTP header digest authentication value from input params?

I have html form with such variables:

  • username
  • realm
  • password
  • nonce
  • algorithm
  • qop
  • nonceCount
  • clientNonce
  • opaque

I want to generate appropriate HTTP header from that values using javascript on the frontend. Actually, I need some javascript library with function, which accepts that params and returns header value. But if there are no such libraries, you can advise some simple way how can I generate it.




samedi 23 septembre 2017

pushobject is not a function emberjs

I've got an odd issue with ember js, when i push an object to a model. Here is my code:

// Environment.js
  EXTEND_PROTOTYPES: {
    // Prevent Ember Data from overriding Date.parse.
    Date: true,
    Array: true,
  }

Route.js

 model () {
  return Ember.RSVP.hash({
    newCollection: this.get('store').createRecord('collection'),
    book1: this.get('store').createRecord('book'),
    book2: this.get('store').createRecord('book')
  })
}

Controller

actions:{
  addCollection(model) {
    model.newCollection.pushObject(model.book1);
    model.newCollection.pushObject(model.book2);
  },
}

Now I'm not sure what the issue, but I'm trying to push the book model into the collection, however, I get an issue with this as the console log suggests that pushObject is not a function. I've updated my Environment.js as other questions have suggested, however this still is an issue.




How to compile my hbs file at my production server?

I'm a server guy with very little knowledge about the client side. My client application is built with ember all I need is to provide a link to my api from the UI. For which I am adding the anchor a tag within .hbs file. I've now idea of how to compile these changes so, that the changes get reflected in my production setup.

Gone though ember-quick-start page and it made me understand what is a model, template, components and all basic stuffs and it teaches me how to run the ember application from my machine.

Now, to get the changes get reflected in a remote machine (in my sample production setup) how should I do? Any help article or guidance with this would be a great relief to me.

Thanks in advance :)




vendredi 22 septembre 2017

EPERM error: operation not permitted, open '..\tmp\build.lock'

A build error is encountered like :EPERM: operation not permitted, open '..\tmp\build.lock' while a reload needs to be done to the web page after editing a javascript file. Ember Js is used at the front end. Windows 10 64bit is the OS. After this error the ember serve stops and the terminal hangs up. But this is working fine with Mac.Please help me out.

Error details are as follws:

EPERM: operation not permitted, open '..\tmp\build.lock'
________________________________________
Error: EPERM: operation not permitted, open '..\tmp\build.lock'
    at Object.fs.openSync (fs.js:558:18)
    at Class.preBuild (..\node_modules\ember-cli-rails-addon\index.js:38:10)
    at ..\node_modules\ember-cli\lib\models\builder.js:144:34
    at Array.map (native)
    at Class.processAddonBuildSteps (..\node_modules\ember-cli\lib\models\builder.js:142:43)
    at Class.build (..\node_modules\ember-cli\lib\models\builder.js:163:17)
    at Watcher_build [as build] (..\node_modules\broccoli-sane-watcher\index.js:75:6)
    at Watcher.<anonymous> (..\node_modules\broccoli-sane-watcher\index.js:43:17)
    at tryCatch (..\node_modules\rsvp\dist\rsvp.js:525:12)
    at invokeCallback (..\node_modules\rsvp\dist\rsvp.js:538:13)




Building a conditional Ember helper

I'm trying to build a new conditional helper for my Ember application. Is important mention that I'm using Ember 1.10.1 that uses Handlebars 2.0 and I can't upgrade it, would be great solving the problem with this version of Ember. Before writing here I tried different solutions and debugged the Ember code a lot, I'm near to the solution but probably I'm missing something.

First of all, I tried with the following approach reading the Handlebar documentation:

Ember.Handlebars.registerHelper('helperName', function(conditional, options) {
    if(conditional) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

And here the template:


    print true

    print false


Everything worked fine calling the fn function but the inversion function (used to render the template of the else branch) was actually an object instead of a function.

Then I started debugging the Ember code and I tried to follow the same approach that Ember uses with the if helper, so I ended up with the following:

Ember.Handlebars.registerHelper('helperName', function(condition, options) {

    var permission = Ember.Object.extend({
        can: Ember.computed(function() {
            return condition;
        })
    }).create();

    Ember.Handlebars.helpers.boundIf.helperFunction.call(this, ["can"], permission, options, options.data.buffer);
});

can is the property bound to the if, used to change the template if the property changes, since we are using the boundIf version of the if (that does what I just said).

The problem of this solution, that imho could be the nearest to be correct, is that the property is not computed correctly and the helper prints always the false value. I debugged really a lot without making it working, so any help would be very appreciated and I hope this could be useful for someone else as well.




Best online paid video tutorials for learning emberJs? [on hold]

Which is the best online video tutorials for learning emberJs ?




Redirecting route - what is ember way?

In my app, I require to user to not use the back button of the browser on the last page. For that I find a way to replacing existing url with current page url. so user will stay with same page.

I am using this JS code :

init(){//writing at init

        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', function () {
            history.pushState(null, null, document.URL);
        });
    },

But what is the correct code of ember to replace the above code? what is the correct way to do?

thanks in advance.




Not getting value through call back in Enber js

I am new to Ember JS and any UI framework. Facing below issue so kindly suggest.

I user object (json) having it's group ids (array). Using group Ids I need to pull the group name and details. Using below code to get the details.

Asynchronous call is going through and fetching the data but I an not getting in nameGroup variable.

var nameGroupName = _.filter(user.userGroups, function(group){
     return groupService.GroupDetails(group).then(function(result) {
       return result.name;
     });
});

Kindly suggest.




jeudi 21 septembre 2017

Sails.js + Ember.js

I'm looking for information on connecting Ember.js to Sails.js. It appears many of the existing adapters on GitHub are 3+ years in age and have had not activity. Items such as the SANE Stack are also not maintained. Can someone point me in the right direction? Most articles indicate to use the REST Adapter within Ember.js to connect to RESTful services, but very little info beyond the basics. I would appreciate any information or sites that you may suggest to find such information.




Get table attribute or property value within ember controller

I have an ember application which has a table and a grid component within a page. I have enabled drag and drop feature which drags a value from a particular cell of a table and drops it into the empty space of the grid. As the tables have more than one column, I want to get the index position or I want to know which column's cell is being dragged. I want that index value of column within the controller.

Suppose a table has 3 rows with 3 columns. For all the elements within the first column being dragged, I want to get the index value as 1 similarly for 2nd and 3rd column.

Here is my .hbs code for the table

<table class = "table table-bordered">
        <thead>
            <tr>
                <th colspan="6">Inbound Units</th>
            </tr>
        </thead>
        <tbody>
          
               <tr>
                
                      
                        <td abbr="P1"></td>
                        <td></td>
                        <td></td>
                        <td></td>
                      
                      
                            </tr>
            
        </tbody>
    </table>

As you can see wihtin the table td tag, I have specified abbr attribute. But I have no idea how to get the value of abbr within the controller. Any other way of getting this is also fine.

Thanks !




Keep model data sorted?

My Ember data is database-based, but Ember maintains its own copy. So while the CRUD calls return sorted data always, it gets out-of-sort in Ember when data is added. The obvious fix is to have Ember stay in sync with the database, but that seems to violate the premise of Ember, plus there's no obvious "reloadAll" call.

But there's also no obvious "sortBy" that applies from a model. I did try adding a...

phrasesSorted: Ember.computed.sort('phrases', 'phrase')

to my phrases model, but couldn't figure out how to get it referenced from the component (e.g. doesn't do it.)

What's the Embery-way to easily present data sorted? Is this a case where I need to write a bunch more code - e.g. custom routes and controllers - to do something that seems simple, or just me missing the simple?




how to pass controller data into component and back up in ember js

I have an ember 2.13 app that has a users route fetching a users model. So in the users template I am showing all the users fetched. I also have a users controller that feeds data to an edit form when a user is clicked. I'm using the user controller to do this.

All the code is in a single template but I would like to put the rendering user list and edit user form in two separate components. Let's say I make a render-single-user and edit-user templates. So when a user clicks on a user in rendered using the render-single-user component, data of this user should show up in the dom rendered by edit-user component.

The problem is a component doesn't have access to the route's model or the app's store.

I would be grateful if someone would tell me how to pass the model and store from controller to the components and also between the render-single-user and edit-user components. And when a user clicks update/save the modified data should travel up to the controller and save the record to the store consequently making a post request to the server.

Screenshots attached.

user view

clicked user




Building website to pull and display data - What framework to use?

[TL;DR at bottom]

Currently I am designing a website to pull and display data. I have never done this before and was wondering what js frame would be best? I was looking at react as it is good for single page applications, and that's all the webpage will be. But it appears that in ember you have to do certain things certain ways which can be beneficial if the website is long term. Does anyone have any experience with both of these frame works? Would they be good frame works to use for this website or should I be using something else?

TL;DR - Making website to pull and display data what js framework should I use.

Thanks.




How to fully rerender a component with ember?

I have a component with helpers inside it to format data. I'd like to recall the helpers when the user changes the lang. I tried to use this.rerender() in the component, but it doesn't work, it doesn't call again the helpers inside the component.

Is there a way to do that ?




How to collect sub arrays are new Arrays using `computed` method?

I have a list of array. which contains sub arrays. how to collect those arrays and return as new array?

here is my try but not works:

transactions:Ember.computed.map('model.cardList', function(card, index ){
        return card.get('transactions');
    },[]), //collecting all sub arrasy but not works!!
    sortedCards:Ember.computed(function(){
        return this.get('model.cardList');//length 4 
    }.property([])),

What is the correct way to collect the sub arrays from parent arrays? it requrie for sorting purpose.

Thanks in advance.

trying here, but nothing works: Twiddle




mercredi 20 septembre 2017

How to change the URL in ember.js by checking platform?

I am new to ember.js.

I want to know about changing url by checking platform. I have two web app for mobile view server and web view server which are created by ember.js and tornado webserver.They are same app but different ui for mobile and web. when i type the url www.something.com in mobile browser, i want to go to the url m.something.com in mobile view server automatically and if i type the www.something.com in desktop browser, it should go to web view server automatically.

I don't know how to do that. Please help me.




Ember js hasmany relationship saving data

I have two models in Ember where one is a collection and the other is book. Collection model has a "hasMany" relationship with "book" and "book" "belongsTo" "collection". So what i want to do is have a form with both models in and store them at the same time.

Collection Model

// collection Model
export default DS.Model.extend({
    name: DS.attr('string'),
    city: DS.attr('string'),
    books: DS.hasMany('book', { async: true })
});

The book model

//book Model
export default DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('string'),
    collection: DS.belongsTo('collection', {async: true})
});

The form

//Collection View
<div class="row">
    <div class="col-sm-12">
        <div class='panel panel-default'>
            <div class='panel-body'>
                <form>
                    <fieldset>
                        <legend>
                            Collection
                        </legend>
                        <div class="row">
                            <div class="col-sm-6">
                                <label for="name" class="col-sm-2">Name</label>
                                <div class="col-sm-10">
                                    
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <label for="city" class="col-sm-2">city</label>
                                <div class="col-sm-10">
                                    
                                </div>
                            </div>
                        </div>
                    </fieldset>
                    <fieldset>
                        <legend>
                            books
                        </legend>
                        <div class="row">
                            <div class="col-sm-6">
                                <label for="title1" class="col-sm-2">title</label>
                                <div class="col-sm-10">
                                    
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <label for="description1" class="col-sm-2">description</label>
                                <div class="col-sm-10">
                                    
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-6">
                                <label for="title2" class="col-sm-2">title</label>
                                <div class="col-sm-10">
                                    
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <label for="description2" class="col-sm-2">description</label>
                                <div class="col-sm-10">
                                    
                                </div>
                            </div>
                        </div>
                    </fieldset>
                    <div class="row">
                        <div class="col-sm-12">
                            <button  class="btn btn-primary">New Collection</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

The controller:

actions:{
    addCollection: function(){
        var name = this.get('collection.name');
        var city = this.get('collection.city');


        var title1 = this.get('book.title1');
        var description1 = this.get('book.description1');
        var title2 = this.get('book.title2');
        var description2 = this.get('book.description2');


        var newCollection = this.store.createRecord('collection', {
            name: name,
            city: city,
        });
    },

As you can see I'm trying to obtain 2 sets of books for this collection, but I'm having trouble on finding the correct procedure to store items to these models. I guess I may have to store the collection model first and then push the individual books to the collection. Is this correct? How would I go about it?




How to get an DOM element outside of ember view?

I am currently working on an application where we are mopving the whole application to ember,but as of now the application is working with JSP and jquery.

My problem is that my ember app is currently getting inserted into a jsp page via an object tag.now i want to know the class of this tag and render the route accordingly.

When i tried fo find $('object'),i am getting nothing.

I tried few other options available but no luck.

My index route is loading home route as of now but i want to load routes on the basis of class available on object tag.

below is my index.js

import Ember from 'ember';

    export default Ember.Route.extend({
        beforeModel() {
        console.log(this);
        this.replaceWith('rentals');
      }
    });

and my jsp has this code snippet in order to add my desired ember application

var url = "../../rdm/ember/dist/index.html";
                if(page = "user")
                {
                    $(".ui-layout-center").html( '<object type="text/html" class="user"></object>');
                    $("object").attr('data',url);
                    mdmCurrentRequestObj = $(".ui-layout-center object");   
                }
                else
                {
                    $(".ui-layout-center").html( '<object type="text/html" class="userprofile"></object>');
                    $("object").attr('data',url);
                    mdmCurrentRequestObj = $(".ui-layout-center object");       
                }




EmberData peekRecord() method

The app I've been putting together looks like a list of stores (with add/edit/delete options), and clicking on a store name takes you to the list of items in that store (again with add/edit/delete). The router:

Router.map(function() {
    this.route('about');
    this.route('stores');
    this.route('shop', function() {
        this.route('items', { path: '/:shop_id/items' });
        this.route('edit', { path: '/:shop_id/edit' });
    });
});

The model:

// app/models/shop.js
import DS from 'ember-data';

export default DS.Model.extend({
  shopName: DS.attr(),
  shopDetails: DS.attr(),
  items: DS.hasMany('item')
});

and:

// app/models/item.js
import DS from 'ember-data';

export default DS.Model.extend({
  itemName: DS.attr(),
  itemDetails: DS.attr(),
  itemPrice: DS.attr(),
  parentShop: DS.belongsTo('shop')
});

Route for the page that displays the list of items is:

// app/routes/shop/items.js
import Ember from 'ember';

export default Ember.Route.extend({
    model(params) {
        return this.get('store').findRecord('shop', params.shop_id, {
            include: 'items'
        });
    }
});

Now as far as I understand before adding an item to a shop I have to call peekRecord():

// app/controllers/shop/items.js
actions: {
    saveItem() {
        let currentShop = this.get('store').peekRecord('shop', /* shop id here */);
        //rest of the code
    }
}

from:

// app/templates/shop/items.hbs
<button type="submit" >Save</button>

The question is, how do I pass the shop id as the second argument for peekRecord()?




How to sort the model array before supply to template

Here is my model, how can i sort it before I send to template?

route.js

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return {
            "fruits":[
            {fruit:"mango",color:"yello"},
            {fruit:"banana",color:"muddy yellow"},
            {fruit:"apple",color:"red"}],
          "prices":[9, 10,5 ]
                }
   } 
});

Twiddle Demo

Any one please update my twiddle? looking for ember approch.

here is my hbs:

<h1>Fruit Prices Sorted here</h1> 
<ul>

    <li> </li>

</ul>

<h1>Fruit Prices Sorted here</h1> 
<ul>

    <li> </li>

</ul>

<h1>Fruit Details Sorted by Alphabetically </h1> 
<ul>

    <li> </li>

</ul>
<br>
<h1>Fruit Color Sorted by Alphabetically </h1> 
<ul>

    <li> </li>

</ul>




mardi 19 septembre 2017

belongsTo relationship empty on save

I have two models that have a relationship, team and teamMember. On a page I'm trying to set it up so that the user can add a new teamMember to a team, but when I'm calling save() it's spitting back that a team must exist, and upon further inspection Ember is not embedding the team in the POST.

team.js

export default DS.Model.extend({
  ...
  teamMember: DS.hasMany('team-member')
}

team-member.js

export default DS.Model.extend({
  ...
  team: DS.belongsTo('team')
}

This is what I have in my route

let teamMember = this.get('store').createRecord('teamMember');
let team = this.get('store').findRecord('team', params.teamId).then((results) => {
  teamMember.set('team', results);

  return results;
});

I pass the team and the teamMember to a component where I can edit the teamMember, and save it.

let teamMember = this.get('teamMember');
// get and set teamMember specific fields
teamMember.save();

When I debug from that line I can say teamMember.get('team') and get all of the data, so it seems to be properly set, but all I get from the Rails API is

{"team_member"=>{"role_id"=>"0", "phone_number"=>"8888888888"}}

And it obviously won't create a team_member without a team to associate it with.

I have a team-member.js serializer:

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    team: { embedded: 'always' }
  }
});

I do have some stuff in an application serializer, so I'm wondering if it's overwriting the data somehow, but when I debug in that it's still not recognizing the existence of the team.




typescript error TS2688 after installing ember-table. Can I not ignore those?

I am using ember with typescript. After installing ember-table, started getting the errors below -

error TS2688: Cannot find type definition file for 'antiscroll'.
error TS2688: Cannot find type definition file for 'jquery-mousewheel'.
error TS2688: Cannot find type definition file for 'jquery-ui'.

while Typed definition for jquery-ui is not there but we do have jueryui on definitelytyped, others are not even available.

I know there is lot of discussion on github (http://ift.tt/2ycfR42) but I see no resolution despite the issue being closed, I may be mistaken though.

Has anyone solved this yet? Since these were installed as dependencies and not used directly, I have no control over defining then as 'any'.

Help needed.




Handlebars.js check if one attribute matches another

I'm using Handlebars.js to display an element depending on whether a string matches the current user's username.

I'm actually looping through a collection blogs and this is where the attribute author comes into play. Regardless, author.username represents some username string and this is available to me. My problem is that if I change user.attributes.username to some pre-defined string, i.e. "martin" then the condition checks out and it displays the element the way I want. But I also have an attribute user.attributes.username and this renders just fine outside the #ifEquals condition. I really want to compare author.username with this attribute, and not some pre-defined string.

How can I compare two attributes, i.e. author.username with user.attributes.username instead of author.username with "martin"?

Both author.username and user.attributes.username have the same value. This doesn't work for me right now but is what I ultimately want:


        
            <a href="#" onClick="return false;"><span class="delete-container" style="cursor: pointer" data-blog-id=""><span class="typcn typcn-arrow-sorted-down hvr-pulse-grow" style="color: gray; font-size: 30px;"></span></span></a>
        


This works but isn't sufficient for my purposes:


        
            <a href="#" onClick="return false;"><span class="delete-container" style="cursor: pointer" data-blog-id=""><span class="typcn typcn-arrow-sorted-down hvr-pulse-grow" style="color: gray; font-size: 30px;"></span></span></a>
        


Handlebars.js Helper:

<script>
    Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
        return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
    });
</script>




How to use adapter in an ember-engines

as the title say, I have some problem understanding how to use an adapter in an ember-engines.
I am currently running my application with ember@2.15, ember-data@2.15 and ember-engines@0.5.14. I already used an adapter in my main application, but if I tried to reproduce a basic adapter in my application, the page is loading indefinitely.
In my route, I call my adapter with the findAll method:

  model()
    {
        "use strict";
         console.log('In my route');
         return this.get('store').findAll('my-adapter-name', {reload: true});
    }

And in my adapter, I respect the syntaxe that I used in my in-app adapter:

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

export default DS.Adapter.extend({

    findAll: function (store, type, sinceToken, snapshotRecordArray)
    {
        console.log("In my adapter");
        return new Ember.RSVP.Promise(function (resolve, reject)
        {
        // I accede to my websocket service here, nothing to do with my question
        });
    },
    /* *
    * My other function, like findRecord, ect...
    */
});

As you can see, I putted some console.log in my code, and I can access to the message in my route, which is in my engine, but I can't access to the message in my adapter, which is also in my engine.
I tried to put a console.log in an adapter in my applicaton, and the message is properly shown, so I am sure this is because I can't access to the adapter in my engine, so if anybody has an idea to how we should configure our adapter in our ember-engines, this would be very appreciated.
For your information, this is an in-repo engines.




forcing navigator.online to false when running tests

I'm writing acceptance tests for an ember application and the application works offline. I wanted to know if there was a way to force navigator.online to false to test certain behaviours when running tests.

Thanks!




Developer workflow: Does it matter which port is used during development?

Are there any differences between choosing this or that port? Are there any standards for picking a port?

I'm just looking for the "why" a particular port was picked to be used. There doesn't appear to be a standard convention for picking a port number(at least in documentation).

The examples in official docs use different port numbers.

  • Create React App docs provide examples using localhost:3000/
  • Django docs provide examples using port 8000/
  • Ember docs provide examples using port 4200/
  • Express docs provide examples using port 3000/
  • Flask docs provide examples using port 5000/
  • Webpack docs provide examples using port 8080/



lundi 18 septembre 2017

How do I add key:value pair in an order in javascript.

I need to add key:value into an object.

var a = {}
a['first'] = [a,bunch,of,stuff]
a['eight'] = [another,bunch,of,stuff]
a['two'] = [more,stuff]

but now variable 'a' contains

{eight: [a,bunch,of,stuff],first: [another,bunch,of,stuff],two: [more,stuff]}

while what I wanted was

{first: [another,bunch,of,stuff], eight: [a,bunch,of,stuff],two:[more,stuff]}

I'm guessing the order is based on the alphabetical order of the keys. This is a problem, because I want to display the data into hbs using {#each model as |key value|} in the same order as I wanted it.




Ember sort property without computed

I've been struggling for a few days with a simple sorted search feature that a want to perform on a guest list for a party app I'm working on.

Searching on internet I came across computed.sort('model', 'sortProps') solution. At the guest list page I have a button that toggles the sort as asc and desc alongside with a search field. The problem is that once I set and attribute with computed it becomes read-only and therefore cannot be set again with the new search key being typed.

As computed was the only way of sorting that I could find, I approached the situation by creating one separated computed list for each filter scenario.

My question is. How can I perform filter and sorting on the same property? What is the best approach? For now I decided to remove the sort and computed. I'm using just the store.filter() which allowed me to reduce a lot code and work-around.

These are the models. Then I have my old/ugly/not-satisfying component approach and finally the new one.

1 event.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  eventDate: DS.attr('date'),
  details: DS.attr('string'),
  guestList: DS.hasMany('guest-list'),
});

2 guest.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  phone: DS.attr('string'),
  email: DS.attr('string'),
  details: DS.attr('string'),
  guestList: DS.hasMany('guest-list'),
});

3 guest-list.js

import DS from 'ember-data';

export default DS.Model.extend({
  info: DS.attr('string'),
  paid: DS.attr('boolean', { defaultValue: false }),
  arrived: DS.attr('boolean', { defaultValue: false }),
  vip: DS.attr('boolean', { defaultValue: false }),
  guest: DS.belongsTo('guest'),
  event: DS.belongsTo('event'),
  timestamp: DS.attr('number'),
});

My old component (ew)

import Ember from 'ember';
import FuzzySearch from 'npm:fuzzy-search';

const { computed } = Ember;

export default Ember.Component.extend({
  sortProps: [`name:asc`],
  currentSort: 'asc',
  display: 'all',
  list: null,

  searchList: null,

  active: {
    all: true,
    paid: false,
    notPaid: false,
    vip: false,
    arrived: false
  },

  all: computed.sort('model', 'sortProps'),
  paid: computed.filterBy('all', 'paid', true),
  notPaid: computed.filterBy('all', 'paid', false),
  vip: computed.filterBy('all', 'vip', true),
  arrived: computed.filterBy('all', 'arrived', true),
  free: computed.filterBy('all', 'free', true),

  filtered: computed('searchList', function() {
    return this.get('searchList');
  }),

  sorted: computed.sort('filtered', 'sortProps'),

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

  setActive(current) {
    this.set('active', {
      all: current === 'all',
      paid: current === 'paid',
      notPaid: current === 'notPaid',
      vip: current === 'vip',
      arrived: current === 'arrived'
    });
  },

  setList({ all, paid, notPaid, vip, arrived, free, filtered, sorted } = {}) {
    this.set('list', {
      all: all || this.get('all'),
      paid: paid || this.get('paid'),
      notPaid: notPaid || this.get('notPaid'),
      vip: vip || this.get('veip'),
      arrived: arrived || this.get('arrived'),
      filtered: filtered || this.get('filtered'),
      sorted: sorted || this.get('sorted')
    });
  },

  actions: {
    sortBy(val) {
      const { sortProps, currentSort } = this;
      const first = sortProps.get('firstObject');
      sortProps.popObject(first);
      const suffix = currentSort === 'asc' ? 'desc' : 'asc';
      this.set('currentSort', suffix);
      sortProps.pushObject(`${val}:${suffix}`);

      this.setList({ sorted: this.get('sorted') });
      this.set('display', 'sorted');
    },

    filterList(val) {
      this.set('display', val);
      this.triggerAction({
        action: 'search',
        target: this
      });

      this.setActive(val);
    },

    search() {
      const key = this.get('search');
      const display = this.display;
      const list = this.get(display).map(item => item._internalModel.__data);

      if (!list.length) return;

      const searcher = new FuzzySearch(list, ['name', 'phone'], {
        caseSensitive: false
      });
      const result = searcher.search(key);
      // this.model.modelName => 'guest' || 'guestmp'
      const filtered = this.model.store.filter(this.model.modelName, guest =>
        result.includes(guest._internalModel.__data)
      );

      this.set('searchList', filtered);

      this.setList({ [display]: this.get('filtered') });
    }
  }
});

My new component (looks a lot nicer but I can't get sorting to work on it)

import Ember from 'ember';
import FuzzySearch from 'npm:fuzzy-search';

const { computed } = Ember;

export default Ember.Component.extend({
  display: 'all',
  active: {
    all: true,
    paid: false,
    notPaid: false,
    vip: false,
    arrived: false
  },

  filteredList: [],
  isFiltered: false,

  setActive(current) {
    this.set('active', {
      all: current === 'all',
      paid: current === 'paid',
      notPaid: current === 'notPaid',
      vip: current === 'vip',
      arrived: current === 'arrived'
    });
  },

  getActive() {
    const active = this.get('active');
    return Object.keys(active).find(key => active[key] === true);
  },

  actions: {
    filterList(val) {
      this.setActive(val);
      this.triggerAction({
        action: 'search',
        target: this
      });
    },

    search() {
      this.set('isFiltered', true);
      const key = this.get('search') ||'';
      const lowerKey = key != '' ? key.toLocaleLowerCase() : key;
      const active = this.getActive();
      const filteredList = this.model.store.filter("guest-list", function(guestListItem) {
        const lname = guestListItem.get("guest").get('name').toLocaleLowerCase();
        const phone = guestListItem.get("guest").get('phone') || '';
        switch (active) {
          case 'paid':
            return (lname.includes(lowerKey) || phone.includes(lowerKey)) && guestListItem.get('paid');
          case 'notPaid':
            return (lname.includes(lowerKey) || phone.includes(lowerKey)) && !guestListItem.get('paid');
          case 'vip':
            return (lname.includes(lowerKey) || phone.includes(lowerKey)) && guestListItem.get('vip');
          case 'arrived':
            return (lname.includes(lowerKey) || phone.includes(lowerKey)) && guestListItem.get('arrived');
          default:
            return lname.includes(lowerKey) || phone.includes(lowerKey);
        }
      });
      this.set('filteredList', filteredList);
    }
  }
});




Ember not retrieving image assets from Rails backend with paperclip and Docker

This is only a problem in production.

I have two Docker hosts, one running an nginx container (serving an Ember app), the other a running a postgres container and a rails-api container. I want to move the the latter-2 containers onto the first Docker host so they can all be hosted on one and I can delete the second Docker host. The Rails-api uses paperclip to upload photos.

In the Ember app production build I point to the rails backend by adding ENV.host = 'dockerhost2.com:3000/' to config/environment.js and host: ENV.host in adapters/application.js.

If I keep everything as it is (with 2 docker hosts) everything weirdly works fine -- that is, images are delivered and displayed on the front end. But if I move all containers to one docker host, the images themselves cannot be retrieved and return a 404.

The image URLs are always 'public/system/000/path/to/Image.jpg'. When I keep things separate (on 2 docker hosts) going to 'http://ift.tt/2yacomG' works perfectly though I don't understand why, as the rails app is serving on port 3000 and on a different host. But when I combine all containers onto 1 docker host the same image URLs return 404 and only works when I go to 'dockerhost1.com:3000/public/system/000/path/to/Image.jpg'. This is perplexing.

Locally everything works beautifully when I put all containers onto 1 docker machine and build the Ember app to point to docker.machine.ip:3000. Going to 'http://ift.tt/2xbBmTa' does indeed find the image though, admittedly, I don't understand why.

My Ember docker-compose.yml

version: '2'
services:
  server:
    image: nginx
    volumes: 
      - ./dist:/usr/share/nginx/html
      - ./nginx-site.conf:/etc/nginx/conf.d/default.conf
    ports:
      - "80:80"

My rails docker-compose.yml

version: '2'
volumes:
  sarahdeyong-postgres:
  images:

services:
  rails: &defaults
    build: .
    image: romanhood/sarahdeyong-api:0.0.1
    volumes:
      - .:/myapp
      - images:/myapp/public/system/
    depends_on:
      - postgres
    entrypoint: ["bundle", "exec", "rails"]

  server:
    <<: *defaults
    tty: true
    stdin_open: true
    command: server -p 3000 -b '0.0.0.0'
    ports:
      - "3000:3000"

  postgres:
    image: postgres
    volumes:
      - sarahdeyong-postgres:/var/lib/postgresql/data
    ports:
      - "5432:5432"

and nginx-site.conf:

# pushState friendly!
# The setup:
#   * website name is `_`
#   * javascript app is located at `/app`

charset utf-8;

tcp_nopush on;
tcp_nodelay off;
client_header_timeout 10s;
client_body_timeout 10s;
client_max_body_size 128k;
reset_timedout_connection on;

gzip on;
gzip_types
    text/css
    text/javascript
    text/xml
    text/plain
    application/javascript
    application/x-javascript
    application/json
    application/xml
    application/rss+xml
    application/atom+xml
    font/truetype
    font/opentype
    image/svg+xml;

server {
  listen 80;
  server_name sarahdeyong;
  root /usr/share/nginx/html;


  # To make sure any assets can get through :)
  location / {
    try_files $uri @rewrites;
  }

  # If no asset matches, send it to your javascript app. Hopefully it's a route in the app!
  location @rewrites {
    rewrite ^(.+)$ /index.html last;
  }
}

How can I get my images to retrieve and display properly in my Ember app?




Access request parameters in URL in ember page

I am using Ember.js in my application. In a .jsp page i have a button and when I click on the button i call the url = "emberapp/myproject/routename?isFromJSP=true&data=[1,2]".

This correctly routes to my "routename".

The problem is, I want to read the boolean parameter (isFromJSP) and list parameter (data) in my controller or route. How to do so?

Thanks for the help in advance.




How to load data from API in parts using ember (ajax)

I have a problem while creating my app with Ember Infinity addon. I am using punkapi and ember infinity addon.

In my app I want to display a number of beers (let’s say 10 beers) and then, while scrolling to the bottom load next 10 beers and so on. Punkapi by default loads 25 beers and allows me to load max 80 beers (there are about 250 beers in API). So the URL looks kind of this: http://ift.tt/2xbx1Qc

Ember Infinity creates the very same URL, so it’s also limited to 80 beers. And paging doesn’t work, because when I scroll to the very bottom, it says that all content has been loaded.

My question is: How do I load 10 beers from API and then load next 10 and next 10 until the end, while scrolling to the bottom of the list?

Here’s my beer adapter:

import Application from ‘./application’;

export default Application.extend({
pathForType(){
return 'beers';
}
});

My beers route:

import Ember from ‘ember’; import InfinityRoute from “ember-infinity/mixins/route”;
export default Ember.Route.extend(InfinityRoute, {
model: function() {
return this.infinityModel(‘beer’, { perPage: 80, startingPage: 1 });
}
});

And my beer template:


<h 3></h 3>
<h 3></h 3>








How to prevent images from reloading when leaving "display: none"

I am writing an Ember.js web-application, designed to be the user interface of an automation system, that polls data from the LAN server every two seconds in order to have on display always the "live" process data. This application is accessible from a wirless hotspot, to allow registered users to browse it, so potentially any device (tablets, smartphones, laptops...) could be the actual client.

On some pages, there are icons that change according to some conditions, and to implement this effect I declared several img tags, and I make the ones I dont need invisible by styling it with CSS display: none.

In HTML:

<img class="icon-active" src="/images/icon1.jpg" />
<img class="icon-inactive" src="/images/icon2.jpg" />

In Javascript, every two seconds:

var visibleElement = null;
var invisibleElement = null;

if( this.get("whatever").active == true )
{
    visibleElement = this.element.getElementsByClassName("icon-active")[0];
    invisibleElement = this.element.getElementsByClassName("icon-inactive")[0];
}
else
{
    visibleElement = this.element.getElementsByClassName("icon-inactive")[0];
    invisibleElement = this.element.getElementsByClassName("icon-active")[0];
}

visibleElement.style.display = null;
invisibleElement.style.display = "none";

Everything works fine, on laptops and tablets, but on some smarthphones, the images are loaded every time I set visibleElement.style.display = null;, it means, every two seconds, the visible icon is GETted again and again from server.

I dont want it to happen at first to reduce data traffic, that is not a problem at all, but I don't like fetching resources even if not required, second, the image reload generates an annoying flicker effect, that is really unlookable.

How can I force every client to cache images as tablets and laptops do?




Ember Js nested forms

Currently I have a form called a "form A", I've created a number of views for this form, an edit, create and list. I want to be able to create a form called "form B", that will pull through "form A's ID" as a parent ID. To enable me to have a list of all form B under a "form A" (essential a one to many relationship). So at the moment under my list for "form A" I have this link for each item:

 <!--Link to a controller -->
      <span class="btn btn-primary"> form b </span> 


Here is also my router

 this.route('form-a', function() {
    this.route('new');
    this.route('listing');
    this.route('edit', {path: '/edit/:form-a_id' });
    this.route('form-b', function() {
      this.route('listing', {path: '/listing/:form-a_id'});
      this.route('new');
    });
  });

So I'm trying to pull through the Id of form-a for the listing. However I'm kind of stuck here as I'm unsure how what to do next and how to correctly pull through "form a" Id in the listing controller and the use it as a parent ID for each "form B". Is there a better way to have nested forms with one too many relationships or am I going about it in the best way?

I hope someone can help as this issue as I have hit the coding wall. If you need any clarifications please ask as I know I'm usually terrible at describing my issues.




dimanche 17 septembre 2017

ember-cli-build.js | set broccoli's params deppending of environmnet

I tried to search in google this but without the correct answer if I need to do.

Its a simple question I have my ember-cli-build.js

  /*jshint node:true*/
  /* global require, module */
  var EmberApp = require('ember-cli/lib/broccoli/ember-app');

  module.exports = function(defaults) {
    var app = new EmberApp(defaults, {
      storeConfigInMeta: false,
      minifyJS: {
        enabled: false
      },
      minifyCSS: {
        enabled: false
      }
    });


    return app.toTree();
  };

And I want change the value of minifyJS or minifyCSS deppending if I am running ember in production or dev, how can achieve that ??




ember-data: Allow sideloaded model to contain embedded records that were just created

I’m running into an issue with the REST Adapter/Serializer and EmbeddedRecordsMixin, specifically my app needs to be able to sideload an model’s parent record in create/POST responses, and that parent model contains the child record embedded in a hasMany array. This is resulting in “You cannot update the id index of an InternalModel once set.” errors. heres a simplified version of the JSON structure my api is returning:

// POST /child-model response
{
    "childModel": {
        "id": 1,
        "foo": "Bar"
    },
    "parentModel": {
        "id": 2,
        "children": [
            {
                "id": 1,
                "foo": "Bar"
            }
        ]
    }
}

Is there any way to allow this type of response? Essentially I want ember-data to just treat the embedded child record as just an "update" to the record that was just created, where it is just using it to make the association between it and the parent record.




Ember issues since 2012. Integrating Push to Keep Client Data in Sync, Local Storage Support, Handling Bad Connections and Crashes

I found this post from 2012 http://ift.tt/2xIc425.

Since then something is changed, but not these points:

  • Low Hanging Fruit - Integrating Push to Keep Client Data in Sync All complex applications allow data manipulation outside of user interaction. I mean not all data changes are done by users sitting on there devices. The server may be syncing something in the background which brings in new data. How is the client going to know about it? Is it periodically polling the server? That's crazy. It's easy to write code that pushes all changes. It should be equally easy to push that data into data store regardless of what push service you're using. Ember-data stores should define a simple interface to accept messages over push. Perhaps, the store itself is a web socket client which can be connected to your push stream. There are many different ways to do this. Everyone will solve this uncomplicated problem in the same way. This is exactly why the framework should do it. Ideally, there should be no problems if you switch from Websockets/Pusher/Faye/PubNub/Boxcar/etc. The messages always arrive.

  • Low Hanging Fruit - Local Storage Support in Ember Data Loading screens blow. I downloaded the data. I shouldn't have to keep going to the server to get it again. You are probably using HTTP caching, but that still creates network requests. Getting good performance means cutting down on network requests. It's not very complicated to do in Backbone. Ember data should support local storage by default. For example, you create your store and you can set storedLocally: false if you don't want it stored. I think that adding local storage to support to the framework and enabling it by default would be a major win. Our app is dealing with a lot of data. Loading in data takes time and reduces performance. We only want to download that data once.

  • Ambitious Addition - Handling Bad Connections and Crashes: Gateway to Offline Support Network connections go down. Browsers crash. These things happen. We have the tools to make applications failure resistant. Let's take your basic todo list application. The user adds a todo and for some reason the server is down. What happens? Do we just say "opps, sorry. Please try again." I don't think so. The framework itself can handle these cases. Here is a proposed solution. Use a messaging queue backed by local storage to buffer requests to the backend API. Requests that match a set of failure conditions (503, 504, or timeouts) are enqueued again and will be tried again later. This is a step towards offline support at the data layer. There has been some discussion about this. There are few things in the way. A request/operation object needs to introduced. This object is persisted in the queue. The adapter takes the request objects then does whatever logic is needed and sends them to the server. These objects would need to be tied to records as well. Since operations to individual records are being tracked, this means you can cancel operations to specific records. There are also race conditions. Hell, there are lot of complicated things to worry about, but solving this problem is massive. Imagine if applications simply got support for this by using Ember. Boom, your application has some level of fault tolerance and it may even save you a few customers. I'd say this is hardest problem to work on but the pay off is fantastic.

Maybe I'm wrong, but is there a way today to handle these problems?




Ember 2, Maybe I did not understand the use and purpose of ember-pouch. Perhaps not useful for what I have to do?

I have a simply application with ember-data that uses DS.JSONAPIAdapter in adapters/application.js because I'm using a backend with JSON API.

import DS from "ember-data";
import DataAdapterMixin from "ember-simple-auth/mixins/data-adapter-mixin";
import ENV from "../config/environment";

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
  host: `${ENV.API_HOST}`,

  namespace: "api"
});

Now I need for some models (and in some scenarios) the user can use my application also in offline mode.

So I thought at pouchdb and ember-pouch. But maybe I was wrong.

Let's say I today write a new post and click the save() button. Now my post is saved through ember-data which is online and says to my server backend to save it through application adapter.

Now my server can save or not this post (maybe it can refuse it because of many words or maybe other validations server-side only).

So after save() my server can say NO! to my client (and to ember-data) or maybe YES!: so I have logical, business operations in my server backend.

With ember-pouch I don't understand:

  • I really need ember-pouch for this problem?
  • how to backup data in client (when offline) just for some models (let's say post and category and tags);
  • how to add ember-pouch just to handle offline mode and retry operations when online for that models using my server backend (and also a couchdb one just for ember-pouch);
  • maybe I'm wrong because any application that uses ember-pouch has to do without the server using only couchdb one? So all the logic is just in client (ember) side? Is this one the right way?
  • how to add ember-pouch in an application just for some models using belongsTo relationship with standard ember-data models?



Reload ember model

Hi I'm a little confused how ember works, I've got a app I'm creating which is to list tasks for a particular user. Here is my model:

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    location: DS.attr('string'),
    date: DS.attr('date'),
    archive: DS.attr('boolean'),
    user: DS.attr('string'),
});

That is for when i add a task to the task list. However for when I get all the tasks in my tasklist i use this in my route:

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

For my filtering of all the users for the tasks I've add this to my controller:

filteredModel: Ember.computed('model', function(){
        let model = this.get('model');

        return model.filter(function(item){
            return item.data.user == this.get('session.user.email');
        });

    }),

All of this works fine. However when I add a new task to the task list, it doesnt update my tasks list, so I have to reload my page. Can this be done automatically, without refreshing my page?




Ember fire filter data in controller

I'm new to ember, what I've created is a task manager app in Ember. I've got a model for tasks which is the following:

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    location: DS.attr('string'),
    date: DS.attr('date'),
    archive: DS.attr('boolean'),
});

I've also got it to show all the tasks for this model in a tasklist page. However I'm currently having issues of filtering only the tasks where archive is not equal to true.

In my tasklist route I've got this to pull through my task

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

However i need this to filter all tasks where archive is equal to false. I do I add this here or into my controller.




samedi 16 septembre 2017

React.js purpose

I spent hours to find out the real purpose React.js and the difference of this from other JS frameworks.

Please, explain me the real pros and cons of React.js in comaprison with Vue.js, Angular.js, Ember.js and other. Thank you




Ember not setting range slider value

In a form, in a table, I have...

<tr><td>Score (-10 to +10):</td><td><br/>Score: </td></tr>

This almost works; the correct value is reported below the slider, and any value set using the slider is stored correctly. But the slider is not initialized with the value correctly. If I replace the binding name with a constant (e.g. "7"), that does initialize properly.

This looks like an Ember bug, in that this same format works for other input types and it does report it correctly; it's just the initialization that's wrong. But it seems kind-of big to be wrong, so there must be some secret magical incantation experienced users know, that I'm just ignorant of. How do I get this to initialize?




Load relationship model in Ember data

I have certain doubts with respect to Ember Data. I have a post and comments model.

//post.js
comments: DS.hasMany('comment')

//blog.js
post: DS.belongsTo('post')

I can create a comment for a particular "post" using

let blogPost = this.get('store').findRecord('post', 1);
let comment = this.get('store').createRecord('comment', {
   post: blogPost
});

But how can i fetch all the comments for a particular post? Like, I have multiple posts which has many comments and i want all the comments for a particular post id, say posts/id/comments

What is the right way to fetch the comments for a particular post id from the store?

Thanks in advance.




How to stop Ember CLI's http-mock server throwing an error when there are websockets in one of the server files?

I have a websocket in one of my http-mock server files initialised as follows:

var WebSocketServer = require('ws').Server;
var socketServer = new WebSocketServer({port: 13434, path: "/update"});

and later in the file I have the following happen on connection:

socketServer.on('connection', function(ws) {
    ws.on('close', function(message) {
        clearInterval(sendResults);
    });

    ws.on('message', function(message) {
        handleClientMessage(ws, message);
    });

    sendResults = setInterval(function() {
        ws.send(JSON.stringify(getResultsFromEntries()));
    }, resultInterval);
});

However, whenever I edit any of the server files I get the following error:

File changed: "mocks/entry.js"

Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE 0.0.0.0:13434
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at Server._listen2 (net.js:1250:14)
    at listen (net.js:1286:10)
    at net.js:1395:9
    at nextTickCallbackWith3Args (node.js:453:9)
    at process._tickCallback (node.js:359:17)

I'm guessing I need to detect when the file change happens and close the current websocket connection. On process exit doesn't seem to get called until the server dies, and then process.on('exit', function() {}) is called the number of times the server has refreshed. It doesn't bother me too much as I have a script that restarts ember server if it goes down, but other developers don't like the ember server going down when they edit a server file. Any ideas?




Ember computed property on a DS model record is not firing when the record is changed

Ex:

I have model/test.js

export default Model.extend({
  name: attr('string'),
  email: attr('string'),
  address: attr('string'),
  age: attr(),
  phone: attr()
});

In component.js

list: computed('model.{}', function() { });

Fetching data in route and passing it to the template. In child component i am trying to access it. initially data passed will be like

{
  'data': {
    name: 'test'
  }
}

later sending data as

{
  'data': {
    name: 'test',
    email: 'test@gmail.com',
    address: 'XYZ',
    age: 10,
    phone: 423423
  }
}

But in computed property it is not listening second updated data. I want to listen dynamically each property in model. It will work if i give like

list: computed('model.{name,email,address,age,phone}', function() { });

But i want some other solution for it. Dynamically need to listen each property in model object.




vendredi 15 septembre 2017

Ember.js route transitionTo method not working

I have a nested route, and from the action I am transitioning to a different route with query-params, but transitionTo does nothing, doesn't even report an error.

The helper works fine, though. But I need to do it with an action.

routes.js:

this.route('parent-route', function() {
    this.route('child-route1');
    this.route('child-route2', {path: '/child-route1/child-route2/:param1/:param2'});
  });

child-route1:

actions: {
    doTransit() {
        this.transitionTo('parent-route.child-route2', {query-params: {'param1': '1', 'param2': '2'}});
    }
}

I have never seen this problem before, what could I be doing wrong?

May be the extra route-name I put in the routes.js file in child-route2? But I need that path there so the URL shows that stuff. Any help, please?




Resolving promise doesn't show data in template

I have tried several versions/attempts to create and return a RSVP.Promise as a param to my template.

All the console.log give reasonable values, so the promises are resolving. The problem I have (which is then also the question) is how to return that resolving values to my template.

Here are the versions I've tried:

// in controller.js
testA: Ember.computed('sessionAccount.account.id', function() {
    let _this = this;
    let promise = new Ember.RSVP.Promise(function(resolve, reject) {
        _this.get('store').findAll('accounts2workgroup').then(function(a2ws) {
            let workgroups = [];
            a2ws.forEach(function(a2w){
                if(a2w.get('rights')>1) {
                    workgroups.push(a2w.get('workgroup'));
                }
            });
            console.log(workgroups);
            _this.set('wgAsAdmin', workgroups); // this works
            resolve(Ember.A(workgroups));  //=> [Object] in rendered template
            // return workgroups; // no, not that way
        });
    });

    promise.then(function(data) {
        console.log('did resolve');
        console.log(data);
    })

    return promise; 
}).property('sessionAccount.account.id'),

testB: Ember.computed('sessionAccount.account.id', function() {
    return new Ember.RSVP.Promise(function(resolve, reject) {
    let workgroups = Ember.ArrayProxy.create([{'label': 'TestB Label'}]);
        resolve(workgroups);

    });
}),

testC: Ember.computed(function() {
    return this.store.findAll('artists2workgroup').then(function(a2ws) {
            let workgroups = [];
            a2ws.forEach(function(a2w){
                if(a2w.get('rights')>1) {
                    workgroups.push(a2w.get('workgroup'));
                }
            });
            console.log(workgroups);
            return workgroups; //=> [Object] in rendered
    });
}),

testD: Ember.computed(function() {
    return this.store.findAll('workgroup'); // this of course works, but that's not what I want...
}),

in my template I test all my tests like so:

<h4>TestB</h4>

        <br>
        <br>

testB: <br>
testB.length: <br>

and all (but the last testD obviously) render to

TestB
testB: [object Object]
testB.length:

though I would expect/want them to show

TestB
<DS.PromiseObject:ember1117>
BB-Promotion
testB: <DS.PromiseObject:ember1117>
testB.length: 1

I know there are ways around that (I can set another property when resolving f.e.), but want to do it the right way and learn how to do this. And I know, that these examples don't make too much sense. That's just the basic functionality, it will be enhanced once I get this running.




Route page without ID - How to use another field?

I am trying to access a specific route with a specific field in my model.

All examples that I found in Ember's community use ID, but I am trying to use another one (which I will make sure to be unique).

My route config:

Router.map(function() {
  this.route('create-wedding');
  this.route('weddings');
  this.route('wedding', { path: 'wedding/:pageName' });
});

My link to the route:

Access

Try to get the record:

model(params) {
  return this.store.query('wedding', { orderBy: 'pageName', equalTo: params.pageName });
}

But, how to get the record for the specific param "pageName" in my Route model? And how to get the same record when the user access the page directly from the URL?

Thanks in advance




How to get event Handler for stop sharing button in chrome in emberjs

I am using twilio API to implementing screen sharing in emberjs app, I successfully able to share the screen and also able to toggle on stopping it, code mentioned as below

this.get('detectRtc').isChromeExtensionAvailable(available => {
    if (available) {
      const { twilioParticipant } = this.get('participant')

      if (this.get('stream') && this.get('stream').active) {
        this.get('streamTrack').stop()
        this.get('userMedia.mediaStream')
        .removeTrack(this.get('streamTrack'))
        this.set('isEnabled', false)
        twilioParticipant.removeTrack(this.get('streamTrack'))
      } else {
        this.get('detectRtc').getSourceId(sourceId => {
          // "cancel" button is clicked
          if (sourceId !== 'PermissionDeniedError') {
            // "share" button is clicked extension returns sourceId
            this.get('userMedia')
            .getScreen(sourceId)
            .then(mediaStream => {
              this.set('isEnabled', true)
              this.set('stream', mediaStream)
              this.set('streamTrack', mediaStream.getVideoTracks()[0])
              twilioParticipant.addTrack(mediaStream.getVideoTracks()[0])
            })
            .catch(() => { /* do nothing, but return something */ })
          }
        })
      }
    } else {
      this.get('flash').status(
        'base',
        this.get('intl').t('chromeExtension.install'),
        {
          icon: 'alert-circle',
          push: true
        }
      )
      // TODO Show the system popup to install chrome extension from web store
      // !!chrome.webstore &&
      // !!chrome.webstore.install &&
      // chrome.webstore.install(this.webStoreUrl)
    }
  })

So the issue I'm facing is with the stop sharing button which is at the bottom of the app as mentioned in screenshot below enter image description here

I need a way to listen to an event handler and execute the some code while clicking on the stop sharing screen, I know there is one onended event Handler is there as mentioned in MediaStreamTrack docs, but don't know how to use, any help will be highly appreciated.

http://ift.tt/1q4huVd