mercredi 30 novembre 2016

Binding HTML Input value in Ember v1.12 Component

I need to use an HTML input in a component and need the value to be bound.The input helper causes various bugs when used on certain mobile devices, so that cannot be used.

The input that works in Ember 1.13 or higher.

component/name-input.hbs

<input type="text" value= onChange=>

component/name-input.js

export default Ember.Component.extend({
    name: 'Jim',
    actions: {
        nameDidChange: function(value) {
            this.set('name', value);
        }
    }
});

How do I use an HTML input in Ember 1.12 and still maintain the functionality?

I tried something like this but the input value is not passed to component's action:

component/name-input.hbs

<input type="text" value= >

component/name-input.js

export default Ember.Component.extend({
    name: 'Dwight',
    actions: {
        nameDidChange: function(value) {
            this.set('name', value);
        }
    }
});

Here are two Twiddles, one in 1.13 that works as expected and one in 1.12 that does not work.

Twiddle - 1.13

Twiddle - 1.12




EmberJs - and array of Class instances

I've defined a class like below

const OpenedCaseStatus = Ember.Object.extend({
  caseid: -1,
  isActive: false,
  selectedTabIndex : -1      
});

export default OpenedCaseInfo;

In my caseInfo service I have created an array openedCases which contains instances of class OpenedCaseStatus.

In one of my component I am injecting the caseInfo service and then in my template I am trying to print case information like:

<div>
    <ul>
        
            <li>caseStatus.caseid</li>
        
    </ul>    
</div>    

But this is not printing the data. Earlier it was working when I was populating the openedCases array with anonymous objects like below:

this.get('openedCases').pushObject({caseid: 1, isActive: true, selectedTabIndex: 0});
this.get('openedCases').pushObject({caseid: 2, isActive: false, selectedTabIndex: 1});
this.get('openedCases').pushObject({caseid: 3, isActive: true, selectedTabIndex: 3});

My question is why is not working with class instances. Is there any alternative?




Emberjs create new model after saving

This seems extremely trivial and I feel awkward asking but I can't seem to create a fresh model after saving the current.

Think todo app, where you want to keep adding new tasks:

I have a very simple route which saves correctly, but doesn't update the frontend with a new model

  model() {
    return RSVP.hash({
      distro: get(this, 'store').createRecord('distro'),
    });
  },

  setupController(controller, models) {
    controller.setProperties(models);
  },

  actions: {
    saveDistro(distro) {
      let newDistro = get(this, 'store').createRecord('distro');

      distro.save().then(() => {
        set(this, 'distro', newDistro);
      });
    },
  }

I think I'm just missing the obvious here?




Dynamically building Ember components from server text

This scenario is hypothetical (sort of) but bear with me:

Imagine that I have a server that manages all communications from clients and customers. A client can send me an email via standard means (outlook, gmail, etc) and I will receive it. My server will parse it and store it as an html string.

 <div>Hello world</div>
 <div>Second Line</div>
 <img width="10px" height="10px" src="http://ift.tt/2g7NbR3">
 <img width="10px" height="20px" src="http://ift.tt/2glGaPz">
 <div>That picture is great</div>

Then when I query for the conversation I receive a list of messages back, which in turn each have their inner html defined above. But sadly none of them have the wonderful trappings of ember :(

Now say that hypothetically I would have liked to wrap that image into its own component, let's say to make its source and dimensions dynamic.



Ideally I would separate out the images and extract the relevant key-value pairs, then throw that handlebars templating into the dom and (assuming I had a dynamic-img component already defined) it would work. However this is not the case.

How can I automagically convert this html text into ember components? Let's say that I have no access to the server.

ember, ember-data, ember-cli => 2.9.x




Ember - Nested child route loses model upon route refresh/reload

I have a nested route, which when refreshed loses the model and displays blank page. Code as below:

Router:

app.Router.map(function(){
    this.resource('main',{path:''}, function(){
        this.route('summary',{path:'/main/summary'},function(){
            this.route('details',{path:'/details'})
        })
    })
})

File structure:

-app
 -route
  -main-route.js
  -main-summary-route.js
  -main-summary-index-route.js
  -main-summary-details-route.js
  -main-loading-route.js

 -controller
  -main-controller.js
  -main-summary-controller.js
  -main-summary-index-controller.js
  -main-summary-details-controller.js

 -templates
  -main
   -summary
    -index.hbs
    -details.bhs
   -summary.hbs
   -loading.hbs
  -main.hbs
  -application.hbs

Brief about code: Templates main.hbs and application.hbs have defined in them. summary.hbs has in it as well, so that when url /main/summary is hit, it shows only contents from summary/index.hbs and when url /main/summary/details is hit, it only shows the one in details by rendering into summary.

My ajax call goes in model hook of "main-summary-route", and while its waiting, i show loading template. "main-summary-details-controller.js" extends from "main-summary-index-controller.js" so that code could be reused. Similarly, "main-summary-details-route.js" gets the same model as the one in "main-summary-route.js" via model hook in details route as -

model: function(){
    return this.modelFor('mainSummary')
}

This is because the ajax call brings together the data for both summary and routes together.

Problem statement: When I hit url main/summary, i get the page and then from there, on a click, goto main/summary/details , i see the page updated with details as well, but when i refresh this (/main/summary/details) manually in browser, the page is blank, i observe that there is no model returned in model hook in details route this time.

My thoughts on solution: I thought that this would work ideally, since on refresh, it would ask for summary route first (being in parent child relation), call ajax (loading alongside) and when data comes through, it would show details. But i guess thats not happening.

I am not getting it, as to whats going wrong. The thought which comes to my mind is that, do i need to probably catch the refresh event in details route and call ajax again, so that it fetches data.

Ember version used - 1.13.0




Ember Data Relationships representations - create record not working

I have a User and a Message model that look like this:

//models/user.js

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

//models/message.js

export default DS.Model.extend({
  body: DS.attr('string'),
  sender: DS.belongsTo('user', { inverse: null }),
  receiver: DS.belongsTo('user', { inverse: null }),
  user: DS.belongsTo('user')
});

Here's how the messages/message route looks like:

//messages/message/route.js

export default Ember.Route.extend({
model(params) {
  return Ember.RSVP.hash({
      messages: this.store.query('message', { filter: {user: params.user}   }),
      user: this.store.findRecord('user', params.user),
    });
  },

  setupController(controller, models) {
    controller.set('messages', models.messages);
    controller.set('user', models.user);
  }
});

and in the router.js I have

this.route('messages', function() {
  this.route('message', { path: ':user' });
});

So basically when you go to /messages/{user_id} you can view all the messages the current user has with the an user that has the {user_id}. Here's a JSON response I get from the server when visiting messages/5

{
"messages": [
  {
    "id": 10,
    "sender": 1,
    "receiver": 5,
    "body": "Hello world!",
    "user": 5
  },
  {
    "id": 7,
    "sender": 1,
    "receiver": 5,
    "body": "Sorry, I don't get it!",
    "user": 5
  },
  {
    "id": 6,
    "sender": 5,
    "receiver": 1,
    "body": "Is it possible?",
    "user": 5
  }
]

}

Now when trying to create a new message there's no sender, receiver or user ids to associate the new record created with, in order to send these over to the server.

Here's what I have in the payload

{
  "body":"New message",
  "sender":null,
  "receiver":null,
  "user":null
}

It's clear I'm doing something wrong with the relationships and not sure how to handle these.




ember-ted-select and ember objects in ember 2.9.1

Im currently using ember-ted-select (http://ift.tt/2g7nz6I) everything is going fine except ember keeps on returning an ember object and not a value onchange.

This is how I set it up to get it to display the label but I have a feeling its wrong:

Controller:

export default Ember.Controller.extend({
  categories:[{
    label: "Web",
    value: "web"
  }, {
    label: "iOS",
    value: "ios"
  }, {
    label: "Android",
    value: "android"
  }, {
    label: "Other",
    value: "other"
  }],
  actions: {
   update(newOption) {
     var opt = JSON.stringify(newOption);
     var selected = JSON.parse(opt);
     this.set('selected', selected.label);
   },
  }
});

HBS:



I also cannot get the selected init with the selected item. Any suggestions would be much appreciated.




Ember Data + JSONAPI - Error: The adapter rejected the commit because it was invalid

I am attempting to submit invalid data via a POST request to a JSONAPI-based API with Ember Data 2.10. The API responds correctly with a 422 code and this payload in the response:

{
  "errors": [{
    "title": "Title can't be blank",
    "id": "title",
    "code": "100",
    "source": {
      "pointer": "/data/attributes/title"
    },
    "status": "422"
  }, {
    "title": "Layout can't be blank",
    "id": "layout",
    "code": "100",
    "source": {
      "pointer": "/data/relationships/layout"
    },
    "status": "422"
  }, {
    "title": "Page type can't be blank",
    "id": "page-type",
    "code": "100",
    "source": {
      "pointer": "/data/attributes/page-type"
    },
    "status": "422"
  }]
}

The errors seem to be loading mostly OK into the model, but I get this error in the console:

ember.debug.js:19160 Error: The adapter rejected the commit because it was invalid
  at ErrorClass.EmberError (ember.debug.js:19083)
  at ErrorClass.AdapterError (errors.js:23)
  at ErrorClass (errors.js:49)
  at Class.handleResponse (rest.js:821)
  at Class.handleResponse (data-adapter-mixin.js:100)
  at Class.superWrapper [as handleResponse] (ember.debug.js:24805)
  at ajaxError (rest.js:1342)
  at Class.hash.error (rest.js:916)
  at fire (jquery.js:3305)
  at Object.fireWith [as rejectWith] (jquery.js:3435)

What is causing this error? Is there something wrong in the JSON payload being returned by the server? One thing that changed recently was the introduction of a pointer to /data/relationships/layout; is Ember Data choking on that?

I may also note that submitting similar bad data via a PATCH request does not trigger this error in the console.

I've also tried this on Ember Data 2.7 before updating to 2.10 to see if that would fix it. Getting the same error with both versions.




vue.js or ember.js - which is suitable for multi page web application

vue.js or ember.js - which client side MVC is best equipped for a multi page web application that tends to draw a huge amount of data from server? Or will any other framework suit the need?




Request in Ember before rendering a route

In my App's localStorage I have stored a token for auth. If the user makes a full reload I need to make a request to the backend to verify this token and to get the username. For all this session stuff I have made an ember service. My application route looks like this:

import Ember from 'ember';
export default Ember.Route.extend({
    currentSession: Ember.inject.service(),
    beforeModel: function(transition) {
        if (transition.targetName !== 'login') {
            const session = this.get('currentSession');
            if (!session.isLoggedIn) {
                this.transitionTo('login');
            }
        }
    }
});

On reload the beforeModel method on the application route is triggered, and I can get the isLoggedIn property from the service.

In the service I have a initializeService method which is called on init:

import Ember from 'ember';
export default Ember.Service.extend({
    store: Ember.inject.service(),
    username: '',
    isLoggedIn: false,

    initializeService: function() {
        const token = localStorage.getItem('Token');
        if (token) {
            const self = this;
            this.get('store').findRecord('session', token).then(function(session) {
                self.set('username', session.get('username'));
                self.set('isLoggedIn', true);
            });
        }
    }.on('init'),
});

This works basically, but there is a race condition because of the async request findReocord. initializeService is not called until this.get('currentSession'); in beforeModel, and while the service is requesting the backend, beforeModel continues. So the if (!session.isLoggedIn) is always true. I tried to initialize the service earlier by using an instance-initializer but that didn't work either. I think I need to make some kind of a synchronous findRecord.




Handling error from server in ember

When i try to handling the response from server, I cant able to read the error status and detail (i.e., those fields are empty)

Below i show my response what i am getting,

{
"message": "Ember Data Request POST http://ift.tt/2gwLxt0 returned a 0?Payload (Empty Content-Type)?",
"name": "Error",
"errors":
[
  {
  "detail": "",
  "status": "0",
  "title": "The backend responded with an error",
  }
],
"description":undefined,
"fileName":undefined
}

Why this fields are empty? what should i do to overcome this?




How to read body parameters from Ember patch request

My Ember logic for updating book

this.store.findRecord('book', 13).then(function (book) {

           book.set('status', 'new');
           book.set('author', 'Someone');
           book.set('rating', '5');
           book.save();

}

My question is, how can I read book.status,book.author& book.rating from server side? I am only getting id i.e 13. Please help me out.




mardi 29 novembre 2016

ember-cli-mirage error: Nothing returned by handler, but handler exists

In the app I'm working with, we have a GET route that validates a user's email address. If the email is invalid, the server responds with:

  • a 200 status code
  • response headers with Content-Type:application/json; charset=utf-8
  • and the response data itself is just a string of "This email is invalid"

I'm trying to simulate this in ember-cli-mirage by doing:

this.get('/ember_api/v1/validations/validate_email', function() {
  return [200, { 'Content-Type': 'application/json' }, "This email is invalid"];

  // also tried this:
  // return new Mirage.Response(200, { 'Content-Type': 'application/json' }, JSON.stringify({"message":"This email is invalid"}));

  // and tried this:
  // return "This email is invalid";
});

The test itself is a button click that fires off this request:

GET "/ember_api/v1/validations/validate_email?email=fakey%40fakefakefake.com&skip_uniq=true"

and the error I'm getting is:

Pretender intercepted GET /ember_api/v1/validations/validate_email?email=tom%40gmail.com&skip_uniq=true but encountered an error: Nothing returned by handler for /ember_api/v1/validations/validate_email?email=tom%40gmail.com&skip_uniq=true. Remember to return [status, headers, body]; in your route handler.

It's asking me to return [status, headers, body], but I'm doing this in my handler and it still throws the error. Is this actually an issue with the response? Do I need to edit my API to actually return a JSONAPI formatted object so I can write the test that way? I feel like I should be able to return a string in my test since that's what the app is doing. Any help is appreciated.




JavaScript Frameworks & REST API Communication

In Ember, the backend models can be defined and the framework can then automatically generate the REST API calls following REST conventions for the models, is there other JavaScript Frameworks which also does this, i.e. automatically generate the REST API calls ?




How to check if an HTML5 validation was triggered using phantomjs?

I am testing my ember app(ember 1.6) using phantomjs. I want to assert that HTML 5 validation is triggered for invalid input. Here is my test:

fillIn('#MyInputField', 'some invalid data');
click('#MyButton');

andThen(function() {
    strictEqual(find('#MyInputField:invalid').length, 1, 'Expected HTML 5 validation triggered!');
});

This works fine when test it using karma when testing in browser. But when testing in phantomjs this fails. I have made screenshot and according to that image there is no HTML 5 validation.




How to assert dom change in ember app which has been executed in run loop?

I am writing test for ember app written in ember 1.6.

Inside controller I have a function executed on promise success:

var me = this;

function onSuccess(result) {

    printSuccessMessage();

    Ember.RSVP.all(promises).then(function(value) {
        Ember.run.later(this, function() {
            clearMessages();
        }, 5000);
    });
}

then inside test I am trying to assert that success message appears:

    fillIn('#MyInputField', 'Some text');
    click('#MyButton');

    andThen(function() {
        strictEqual(find('[data-output="info-message"]').text().trim().indexOf('Done!') >= 0, true, 'Expected success message!');
    });

But the problem is that after click andThen is waiting for run loop to empty. So after this click andThen waits 5 seconds and then execute assertions. In that moment clearMessages() is already executed and message div is cleared so test fails.

Any idea how to assert that this message has certain text?




Ember select2 dropdown option can not be selected

Ember select2 dropdown option can not be selected instead it adds a class name "select2-result-unselectable" to the options list.




Ember 2.8 - link to record is always undefined

I have a page for classes list and a page for single class details.

Whatever I try in link-to helper, I always get an url ending with undefined instead of class id.


Router:

this.route('classes');
this.route('class', { path: '/classes/:id' });

I tried also:

this.route('class', { path: '/class/:id' });
this.route('class', { path: '/class/:class_id' });
this.route('class', { path: '/classes/:class_id' });


Emblem template:

=link-to 'class' class

I tried also:

=link-to 'class' class.id
=link-to 'class' class.class_id
=link-to 'class' class.classId


No syntax seems to work. Any clues?




lundi 28 novembre 2016

Ember - controller not overriding inherited property

I have 2 controllers, one extending the other. Have a prop "order" defined in one of them. And need to change value for that in the other controller which extends the first one. But its not doing so.

Controller A:

define('ControllerA', function(){
    var controller = Ember.Controller.extend({
      order:1
    })
    return controller;
})

Controller B:

define('ControllerB', ['ControllerA'] function(ControllerA){
    var controller = ControllerA.extend({
       order:2
    })
    return controller;
})

This is a very minified version of both controllers. These 2 have different routes which essentially show the same components but with different data, which changes based on order property.

When i go to the 2nd route, i.e B, the value of "order" is not being overridden, i.e. i want it to be 2, but it still picks it up as 1. Am i missing something.




Ember config file after build

I want to take some config properties from a config file instead from index.html(not from the meta generated from config/environment), for example myConfig.js with two variables (lang and host) that can be changed after build. Currently I put that variables in config/enviroment, but i want to separate this variables from this data.

For example:

index.html:

<!DOCTYPE html>
   ...
   <meta name="myapp/config/environment" content="%7B%22modulePrefix%22%3A%22user%22%2C%22environment%22%3A%22development%22%2C%22baseURL%22%3A%22/%22%2C%22locationType%22%3A%22auto%22%2C%22contentSecurityPolicy%22%3A%7B%22default-src%22%3A%22%27none%27%20localhost%22%2C%22script-src%22%3A%22%27self%27%20%27exportApplicationGlobal%22%3Atrue%7D">
   ...
   <script src="myconfig.js" ></script>
   ...
</html>

myconfig.js:

module.exports = function() {

   var MYCONFIG = {
       lang: 'en',
       host: 'http://.....'
   }

   return MYCONFIG ;
};

How this can be done?

Any help will be greatly appriciated




Asynchronous Routing in Ember JS

i am a learner of programming languages such as Dotnet, Java & Android. I have been facing a query that how asynchronous routing can be done in ember js in which we have to create two router files one for fetching the new records from database and the another one for fetching record. I am also searching for new mobile development forum to enhance my Android & IOS programming knowledge.




Is it possible to create a nested adapter in EmberJS?

Am I able to nest Ember Data adapters?

For example, say if I have a model //models/site.js with a template //templates/site.hbs and I want to make a custom query() request to ${ENV.APP.API_HOST}/customers/${org}/sites - as per the docs I can simply customise the query() function at //adapters/site.js.

But what if I have a second template at //templates/sites/show.hbs and I need to query a second distinctly different endpoint such as ${ENV.APP.API_HOST}/customers/${org}/sites/${id} (or any other deeply nested data endpoint) can I setup an adapter under //adapters/sites/show.js? I can't seem to achieve that with Ember Data currently.




Ember JS with remote auth backend (XML response)

Using Ember-Simple-Auth (custom authenticator) and Ember.$.ajax()

Authentication procedure:

  1. Link to authsite.com/login, and log in there
  2. If OK, external website redirects to http://ift.tt/2fJO3NU
  3. I retrieve those parameters
  4. I can get a big XML file with a lot of info by making a request to http://ift.tt/2gpnDQ9 if user is authenticated. Auth backend constraint: this request must come from the same IP as step 2.

I have a problem making this request because:

  1. Not allowed by Access-Control-Allow-Origin
  2. Not JSONP
  3. Cannot enable CORS
  4. Setting crossDomain: true and xhr credentials to true doesn't work either when doing Ember.$.ajax()

What are my options if I want to do everything in the front-end?




How to customize ember-cli build to exclude source code concat

I have rather a large application, right now about 5mb for app.js and 1mb+ in vendor js. I assume it will cross 10mb, our target users are on slow internet and each user have different rights so most of the components are not available to a user.

I was thinking to exclude some big components from build process and load them on demand. So far I liked this idea http://ift.tt/2ftrgaM where it checks if a component is loaded, if not then load them using AJAX

something like

if(!container.hasRegistration(`component:${ componentName }`)){
    $.when(
        $.getScript(`/remote-components/${ componentName }/component.js`),
        $.getScript(`/remote-components/${ componentName }/template.js`)
    ).done(()=> {
        let container = getOwner(this);
        container.register(`component:${ componentName }`, require(`${ ENV.modulePrefix }/components/${ componentName }`).default, {singleton: false});
        this.set('isLoaded', true);
    })
}

I think this can work. But here are two questions

A: How to exclude a component from build process, and stop it from concatenating but also keep them in /dist/components/abc/ folder

B: Separate compile template.hbs to template.js for that component as compiling the template after loading via AJAX will cause huge performance issue.




emberJS Testing when using loading route

When no loading route or a loading template is used, all my tests pass but as soon as I add a loading route, some of my tests fail.

how could I integrate the loading route in my tests ?




Ember.js - The Broccoli Plugin: [object Object] failed with:

I'm new to ember and have set up a sandbox to play around with it. When I type the ember s command I get the error bellow, BUT - and that's the weird thing - the error appears only when I have the Sublime Text open (!?!). If I close the Sublime and type ember s again on the command line everything works fine!

lykos@lykos-VirtualBox:~/My_Projects/ember_sandbox(master)$ ember s
Could not start watchman; falling back to NodeWatcher for file system events.
Visit http://ift.tt/22TlJJ7 for more info.
File: /home/lykos/My_Projects/ember_sandbox/app
The Broccoli Plugin: [object Object] failed with:
Error: watch /home/lykos/My_Projects/ember_sandbox/app ENOSPC
    at exports._errnoException (util.js:1026:11)
    at FSWatcher.start (fs.js:1429:19)
    at Object.fs.watch (fs.js:1456:11)
    at FSMonitor._measure (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/heimdalljs-fs-monitor/index.js:66:21)
    at Object.watch (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/heimdalljs-fs-monitor/index.js:82:30)
    at NodeWatcher.watchdir (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/sane/src/node_watcher.js:144:20)
    at new NodeWatcher (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/sane/src/node_watcher.js:45:8)
    at new sane (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/sane/index.js:17:12)
    at EventEmitter.Watcher_addWatchDir [as addWatchDir] (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/ember-cli-broccoli-sane-watcher/index.js:131:17)
    at /home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/broccoli-builder/lib/builder.js:112:35

The broccoli plugin was instantiated at:
    at WatchedDir.Directory (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/broccoli-source/index.js:14:31)
    at new WatchedDir (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/broccoli-source/index.js:58:13)
    at EmberApp._initOptions (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/lib/broccoli/ember-app.js:200:17)
    at new EmberApp (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/lib/broccoli/ember-app.js:121:8)
    at module.exports (/home/lykos/My_Projects/ember_sandbox/ember-cli-build.js:6:13)
    at CoreObject.setupBroccoliBuilder (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/lib/models/builder.js:70:19)
    at CoreObject.init (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/lib/models/builder.js:50:10)
    at CoreObject.superWrapper [as init] (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/core-object/lib/assign-properties.js:32:18)
    at CoreObject.Class (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/node_modules/core-object/core-object.js:32:33)
    at CoreObject.run (/home/lykos/My_Projects/ember_sandbox/node_modules/ember-cli/lib/tasks/serve.js:15:19)

Livereload server on http://localhost:49152
Serving on http://localhost:4200/

Here are some additional info

$ ember -v
Could not start watchman; falling back to NodeWatcher for file system events.
Visit http://ift.tt/22TlJJ7 for more info.
ember-cli: 2.9.1
node: 6.9.1
os: linux x64

And my package.json file

{
  "name": "ember_sandbox",
  "version": "0.0.0",
  "description": "Small description for ember_sandbox goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.12.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^2.4.1",
    "ember-cli": "2.9.1",
    "ember-cli-app-version": "^2.0.0",
    "ember-cli-babel": "^5.1.7",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-htmlbars": "^1.0.10",
    "ember-cli-htmlbars-inline-precompile": "^0.3.3",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-jshint": "^1.0.4",
    "ember-cli-qunit": "^3.0.1",
    "ember-cli-release": "^0.2.9",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^1.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "^2.9.0",
    "ember-export-application-global": "^1.0.5",
    "ember-load-initializers": "^0.5.1",
    "ember-resolver": "^2.0.3",
    "loader.js": "^4.0.10"
  }
}

Any ideas how to fix this ???




ember route params lost after this.refresh()

In my route, I refresh the page after I update the date, but after refreshing, the params in the url lost.

the url before is like:http://localhost:4200/#/ss/xxx?id=1

the url after is like:http://localhost:4200/#/ss/xxx

the param is important because I need it in my server.

the front script is as follow:

import Ember from 'ember';
export default Ember.Route.extend({
    loginInfo: Ember.inject.service(),
    model: function() {
        return this.store.query('my-stablity-project', {
            creator: this.get('loginInfo').get('staffId'),
            bizId:this.getQueryString("bizId")
        });
    },
    setupController: function(controller, model) {
        this._super(controller, model);
        controller.set('my-project', model);
        let array = model.toArray();
        var str = '';
        for (var i = 0; i < array.length; i++) {
            str += array[i].get('keludeId') + ',';
        }
        this.store.query('kelude-result', {
            keludeIds: str
        }).then(results => {
            controller.set('kelude-result', results);
        });
        this.store.query('kelude-week-result', {
            keludeIds: str
        }).then(results => {
            controller.set('kelude-week-result', results);
        });
    },
    actions: {
        findProjects: function(projectId) {
            this.store.query('kelude-project', {
                projectId: projectId
            });
        },
        updateMySub: function() {
            this.refresh();
        }
    }
});

This situation happens when the action updateMySub is executed.




dimanche 27 novembre 2016

How to handle net::ERR_ADDRESS_UNREACHABLE net::ERR_NETWORK_CHANGED using javascript

While using xhrHttpRequest object, I am registering error, onerror, upload.onerror event handlers to catch various error. But these two errors: net::ERR_ADDRESS_UNREACHABLE net::ERR_NETWORK_CHANGED net::ERR_FILE_NOT_FOUND

are not being caught in the catch block. please help, my requirement is to give specific error in case of file upload,




displaying users avatars list with Ember.js and handlebars

I'm just starting using Ember js and I'm stuck on a very simple thing. I want to display avatars from a users list based on fake API. I manage to get an image when using the absolute path, but nothing when I replace the src with the variable

the var I need to use from my users.json: avatarUrl

here is my users/index.hbs




<img src="absolute-path" alt="avatar">



and my users/index.js

import Ember from 'ember';
export default Ember.Route.extend({
model() {
return Ember.$.ajax('api/v1/users.json');
}
});

This works and displays one avatar. But when I want to use my variable to diplays my avatar list,

<img  alt="avatar">

then it does not work anymore, I got a build error message.

What am I missing? Sorry in advance, it must be something really obvious...

Thanks!




overwrite emberJS methods

I need to overwrite a method in a plugin. Here is what i'm doing

import getUploadMarkdown from 'discourse/lib/utilities';
getUploadMarkdown = function(arg) { //new code }

But i get error getUploadMarkdown is read-only. How can i overwrite a es6 method?




samedi 26 novembre 2016

Ember cli format json data from deep nested relationship

I am very new in Ember and also this is my first question after 1 week for researching. Please correct me if I missed something. Currently, I am using Ember and ROR for my backend, I am building the treeview base on ember-cli-jstree. My expected json data for JStree should be looked like this { "text": "TestCycle", "type": "testcycle_parent", "children": [{ "text": "voluptates", "li_attr": { "id": 12 }, "type": "testcycle", "children": [{ "li_attr": { "data-id": 10 }, "text": "quia", "type": "testsuite", "children": [{ "text": "Automation TestCase", "li_attr": { "testsuite-id": 10 }, "type": "automation", "children": [{ "text": "TC-in", "a_attr": { "auto-id": 1, "testsuite-id": 10, "testcycle-id": 12 }, "type": "automation_testcase" } ] }, { "li_attr": { "testsuite-id": 10 }, "text": "Manual TestCase", "type": "manual", "children": [{ "text": "TC-aaa", "a_attr": { "manual-id": 1, "testsuite-id": 10, "testcycle-id": 12 }, "type": "manual_testcase" }, { "text": "TC-bb", "a_attr": { "manual-id": 2, "testsuite-id": 10, "testcycle-id": 12 }, "type": "manual_testcase" } ] } ] } ] } ] } Project model:

name: DS.attr('string'),
description: DS.attr('string'),
testcycles: DS.hasMany('testcycle', {
    embedded: 'always'
}),
testsuites: DS.hasMany('testsuite', {
    embedded: 'always'
}),

Testcycle model:

name: DS.attr('string'),
testsuites: DS.hasMany('testsuite', {
    embedded: 'always'
}),
project: DS.belongsTo('project', {
    embedded: 'always'
}),

Testsuite model:

name: DS.attr('string'),
testcycle: DS.belongsTo('testcycle', {
    embedded: 'always'
}),
project: DS.belongsTo('project', {
    embedded: 'always'
}),
automations: DS.hasMany('automation', {
    embedded: 'always'
}),
manuals: DS.hasMany('manual', {
    embedded: 'always'
})

Automation model:

name: DS.attr('string'),
value: DS.attr('string'),
testsuite: DS.belongsTo('testsuite', {
    embedded: 'always'
})

The question is how can I get deep nested data when user on project page and format the json jstree. The route for project is:

 model: function(params) {
    return this.store.findRecord('project', params.project_id);
},

and the data which i got on project page is

{
"data": {
    "id": "90",
    "type": "projects",
    "attributes": {
        "name": "Grant, Price and Schneider",
        "description": "Cross-platform full-range process improvement"
    },
    "relationships": {
        "testcycles": {
            "data": [{
                    "id": "12",
                    "type": "testcycles"
                }, {
                    "id": "13",
                    "type": "testcycles"
                }
            ]
        },
        "testsuites": {
            "data": [{
                    "id": "10",
                    "type": "testsuites"
                }, {
                    "id": "11",
                    "type": "testsuites"
                }
            ]
        }
    }
}

} many thanks (I am using JSONAPISerializer adapter)!




Ember Computed Property on Array

I'm an Ember newbie, so forgive me if I've missed something obvious (I've spent time Googling this issue and still can't find a solution) but it seems to me that Ember computed properties aren't working as documented/intended on array properties like length.

I'm trying to build my own queue:

// app/custom-objects/processing-queue-item.js
import Ember from 'ember';

export default Ember.Object.extend({
  payload: null,
  extraContext: null,
  processingState: 'pending', // pending, succeeded, failed
  processingOutcome: null,    // null for pending, result for      succeeded, error for failed

  toString() {
    return `{ProcessingQueueItem: processingState=${this.get('processingState')}, processingOutcome=${this.get('processingOutcome')}, extraContext=${this.get('extraContext')}, payload=${this.get('payload')}}`;
  }
});

// app/custom-objects/processing-queue.js
import Ember from 'ember';
import ProcessingQueueItem from './processing-queue-item';

export default Ember.Object.extend(Ember.Enumerable, {
  queueName: null,

init() {
  this.set('items', []);
  this.get('items');
  this.get('items.length');
  this.get('length'); // Force observation
},

/*
 * Public API
 */

enqueue(payload, extraContext = null) {
 let itemToEnqueue = ProcessingQueueItem.create({ payload: payload, extraContext: extraContext });

 this.get('items').pushObject(itemToEnqueue);
 this.scheduleProcessing();

 return itemToEnqueue;
},

toString() {
  return `{ProcessingQueue: queueName=${this.get('queueName')}, length=${this.get('length')}}`;
},

 /*
  * Internal API
  */

scheduleProcessing() {
  Ember.run(() => {
    this.maybeProcessAnItem();
  });
},

maybeProcessAnItem() {
  console.log(`maybe process an item ${this}`);
},

/*
 * Ember.Enumerable mixin
 */

length: Ember.computed('items.length', function() {
  return this.get('items.length');
}),

nextObject(index, previousObject, context) {
  return this.get('items').nextObject(index, previousObject, context);
}
});

This class is incomplete, but I want to start displaying queue contents in a template to help with debugging but I can't get that to work. Here are my controller and template:

// app/controllers/dashboard.js
import Ember from 'ember';
import ProcessingQueue from '../custom-objects/processing-queue';

export default Ember.Controller.extend({
  init() {
  this._super(...arguments);
  this.set('processingQueue', ProcessingQueue.create({ queueName: 'DashboardQueue' }));
  this.get('processingQueue');
  this.get('processingQueue.length');
  this.get('queueLength');
 },

 queueLength: Ember.computed('processingQueue.length', function() {
   return this.get('processingQueue.length');
 }),
});

// app/templates/dashboard.hbs
<h1>Dashboard</h1>

<h2>Queue Length: ''</h2>

<p></p>




The problem is, in the <h2>Queue Length: ''</h2>, the queue length is always undefined until I add items to the queue. But this is not true, the queue has an empty array and a length of 0. Using $E from the dashboard controller from EmberInspector I can see that $E.get('processingQueue.length') and $E.get('queueLength') are both undefined.

What's strange is that as soon as I add items to the queue, the queue length becomes defined, 1, 2, 3, ... and keeps up and syncs the template as I add queue items. So the first $E.get('processingQueue').enqueue('foo') automagically updates the template to show a queue length of '0', then '1' and so on.

Why is it undefined though before I've enqueued any items? I tried adding gets all over the place according to Unconsumed Computed Properties Do No Trigger Observers but that doesn't seem to help.

Any ideas? It's entirely possible that I misunderstand something about computed properties here, but I don't understand what and why ... I've tried volatile(), [], @each and all that and I can't get that to make a difference either. Something is not right ...

Any help would be hugely appreciated and I'd be willing to add to the Wiki, write a blog post and maybe release my queue as open source as a thank you. :-)

Thanks! And thanks again for making Ember so awesome!




load data in computed properties

I have an ember component which represents a purchase form. You can create old purchase payed in other currency. The converted amount of the purchase depends on the currency chosen and the date of the purchase. So the converted amount is my computed property. The source of the exchange rates is a model backended by an external web service through a custom adapter and they are retrieved by date. This means that when the date changes in the form I may need to call the service. All this happen in the computed property but I know that loading data in it in not a best practice, so I wonder what alternatives I have.




vendredi 25 novembre 2016

Ember computed property depending on service property not updating

In my Ember 2.8 application, I'm establishing a Websocket connection in a service. The connection URL changes when a user is logged in (it then includes the user auth token as a query parameter).

The current user service is simple:

CurrentUserService = Ember.Service.extend(
  name: "current-user"

  user: null

  load: ->
    // Do some stuff
    @set("user", user)
 )

It works exactly as expected, and I use it to display the current users username on the page (among other things).

In the Websocket service, all I do is create a computed property, depending on currentUser.user, that sets up the connection (depending on whether a user is logged in):

ActionCableService = Ember.Service.extend(
  name: "action-cable"

  cable: service()
  currentUser: service()

  testObs: Ember.observer("currentUser", ->
    console.log "currentUser changed, #{ @get("currentUser.user") }"
  )

  consumer: Ember.computed("currentUser.user", ->
     consumerUrl = "ws://localhost:10000/cable"

    if @get("currentUser").user?
      consumerUrl += "?token=#{ @get("currentUser.user.authToken") }"

    console.log(consumerUrl)
    return @get("cable").createConsumer(consumerUrl)
  ) 
)

Problem is, the consumer property never gets updated. It's set once, on page load, and when the user property of the currentUser service changes, consumer is not updated, and neither does my test observer.

When I refresh the page, sometimes the logged in consumerUrl is used, and sometimes it's not.
I'm guessing sometimes the session restoration happens first, and sometimes the action cable service happens first.

What I expected to happen when the action cable service gets loaded first is:

  1. Action cable service gets loaded, no current user set yet, connect to public websocket
  2. Logic that handles restoring user from session data fires, sets currentUser.user (this happens, I can see the username on my page)
  3. The consumer computed property notices the currentUser.user change and connects to the private consumerUrl (does not happen)

I can very easily solve this problem in a way that does not depend on computed properties, but I would like to know what went wrong here.




Binding multiple actions in controller in ember

I designed a mockup for a website that has a sidebar with a menu that appears on mouseEnter, and disappears on mouseLeave. This was mocked up with jQuery, though now I'm trying to recreate this functionality using Ember. I have this working with mouseEnter correctly so far, but I can't figure out how to also bind mouseLeave.

From what I've read so far, implementing a View seems to be the answer though, since view's are deprecated I'm not sure how to go about this.

Here's what I have so far:

/app/controllers/sidebar.js

import Ember from 'ember';

export default Ember.Controller.extend({
  title: 'Ticket Log',
  menu_showing: false,
  actions: {
    toggleMenu: function () {
      this.set('menu_showing', !this.get('menu_showing'));
      console.log(this.get('menu_showing'));
    }
  }
});

/app/templates/sidebar.hbs

<div  id="sidebar" class="panel panel-default">
  
    <div id="sidebar-menu">
      <div id="sidebar-menu-buttons">
        <button id="sidebar-menu-toggle" type="button" class="btn btn-default glyphicon glyphicon-menu-hamburger"></button>
        <button id="sidebar-menu-lock" type="button" class="btn btn-default glyphicon glyphicon-lock"></button>
      </div>
      <div id="sidebar-menu-pills" class="panel panel-default">
        <div class="panel-body">
          <ul class="nav nav-pills nav-stacked">
            <li class="active"><a href="#">Ticket Log</a></li>
            <li><a href="#">Customer Info</a></li>
            <li><a href="#">Asset Info</a></li>
          </ul>
        </div>
      </div>
    </div>
  
  
  
</div>




Getting records by attribute in ember

In my application route I get the current session and user.

/routes/application.js

import Ember from 'ember';

export default Ember.Route.extend({

    beforeModel: function() {
      return this.get('session').fetch().catch(function() {});
    },
    model () {
      return this.store.findRecord('user', this.get('session.currentUser.uid'));
    }
});

My models are set up like so:

/models/bet.js

import DS from 'ember-data';

export default DS.Model.extend({
  created: DS.attr('date'),
  user: DS.belongsTo('user', { async: false })
});

/models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
  email: DS.attr('string'),
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  bets: DS.hasMany('bet', { async: true })
});

In my /bets route I'd like to load only the bets where user == session.currentUser.uid or a similar way to get only the bets that belongTo the current user.

I've tried finding the best way to do this without results.




Getting specific item with findRecord

I'm new at ember and as first app I'm trying to build a little online shop. I can receive "all products" as product overview but not one specific product by id.

I have following in the router.js:

Router.map(function() {
  this.route('products');
  this.route('product', {path: 'products/:product_id'});
});

My products.js (wich works):

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.get('store').query('product', {});
  }
});

And the product.js (wich does generate the problem):

import Ember from 'ember';

export default Ember.Route.extend({
  model(params){
    return this.store.findRecord('product', params.product_id);
  }
});

The project is available under http://ift.tt/2gopO5z

Maybe you could help me out here. Thanks in advance! :)




How do I stop bootstraps table background color setting for print media over riding my class setting

I am using twitter-bootstrap as the main styling for my HTML.

I have a table which is generated (from an ember app) and each cell of the table has a background color set to indicate a certain state. The color is set with a class selector.

This work perfect for the screen, but when printing I just get white background color, because bootstrap defines the following:

@media print {
  .table td, .table th {
    background-color: #fff !important;
  }
}

My html looks something like this:

<table class-"table table-condensed>
   <tr>
     <td class="bg-color1>Content</td>
     <td class="bg-color2>Content</td>
   </tr>
</table>

My css looks like this:

.bg-color1 {
  background-color: #ababab;
}
.bg-color2 {
  background-color: #bababa;
}
@media print {
 .bg-color1 {
   background-color: #ababab;
 }
 .bg-color2 {
   background-color: #bababa;
 }
}

It still doesn't work if I use !important in the print media class descriptions. Also if I add the following to 'undo' the td th setting from bootstrap it doesn't work as this takes precedence over my class settings so I still don't get the color when printed

@media print {
 .table td, .table th {
   background-color: initial !important;
  }
}

There seems no way to get colored backgrounds with class selector using bootstrap. Does anyone have a solution for this.




Handlebars : triple mustaches print all html if any html tag is incomplete

I want to remove HTML tags from the text in handlebars. So I am using triple braces '}', which is working fine.

But the problem is that I am doing the substring of text when its length is more than 90. And after doing that HTML tags in text get incomplete. For example:-

Original text was :-

We will soon start with Mocha , Chai and Karma <a href='http://ift.tt/2fysIqM' target='_blank'>@Shivam</a> <a href='http://ift.tt/2gc77Tq' target='_blank'>@Punit</a> <a href='http://ift.tt/2fyAQrd' target='_blank'>@Nitin</a> <a href='http://ift.tt/2gccYIl' target='_blank'>@Ishimdar</a> 

After substring it got:-

We will soon start with Mocha , Chai and Karma <a href='http://ift.tt/2fyz9KE

Now when I put this new text in triple braces then handlebars not behaving this like HTML and print all HTML code of my HTML file, which is after that text.

Any help appreciated Regards Shivam




Can I use Atmosphere framework for websockets with ember js on client side?

I want to implement push-notification feature in Spring for my project. I want to implement this using WebSockets. When I did some research on this regarding the ways to implement a WebSocket based notification feature in Spring, I came across the Atmosphere framework. I went through their tutorial on this page . I saw that on the client side they are using atmosphere.js but my issue that in my project the client side is done in Ember JS. So can someone please tell me if there is a way I can use Atmosphere at server side and keep my client side with Ember? If yes how shall I integrate Ember with Atmosphere?




How to get property with argument from controller

I want to get the property defined in my controller. I do need a property, cause I am using it also in a template, so please do not suggest me to change my implementation. I am just asking if it is possible.

My Implementation:

export default Ember.ObjectController.extend({
    canNotSave: function(lookup) {
        console.log(lookup);
        if(lookup === true) {
            //.... DO SOMETHING
            return true;
        }
        else {
            return false;
        }
    }.property(),

    actions: {
        close: function() {
          var canNotSave = this.get('canNotSave',true); //<- This is not working
          if(canNotSave)
          {
            //.... DO SOMETHING
          }
        }
    },
});

Is this possible to do something like this? And how?




set dynamic JSON key value pairs in ember

I am having a list of array elements (i.e., ["test1","test2","test3"]), now i have to set this values as key for json data, how to set this?

I tries this,

var listOfStoreValue = [ "test1", "test2", "test3"];
listOfJSONObj[j] = [];
for (k = 0; k < Response.length ; k++) 
{
 listOfJSONObj[j].push({listOfStoreValue[j] : Response.get(Value[j])[k]});
}

but it shows syntax error!




Unable to give SOAP call in Node JS

I am referring below code for calling SOAP API using node js Below is my code

    var soapWSDL = "http://test.com?wsdl";
var params = {
    Username:’test’,
    Password:'test',
};

var callback = function (res, error, retval) {
 if (error) {
   console.log(error);
   return;
 }
 console.log(retval);
 res.send(retval);
}


 soap.createClient(soapWSDL, params,function (err, client) {
       if (err) {
         return callback(res, err, null);
       }

     client.setSecurity(new soap.BasicAuthSecurity('test','test’));

      var args = {Fields: 'test };

      client.WorksheetFetch(args, function(err, result) {
        callback(err, result);
      });

But I am getting “Request was unauthorized “error although I have given right credentials.




SwiperSlider, Gallery with thumbs and loop enabled breaks SwiperSlider completly

SwiperSlider breaks with loop: true and thumbs enabled.

my code is this:

var galleryTop = new Swiper('.gallery-top', {
  spaceBetween: 15,
  slidesPerView: 2,
  centeredSlides: true,
  loop: true
});

var galleryThumbs = new Swiper('.gallery-thumbs', {
  spaceBetween: 10,
  centeredSlides: true,
  slidesPerView: 'auto',
  touchRatio: 0.2,
  slideToClickedSlide: true,
  loop: true
});

galleryTop.params.control = galleryThumbs;
galleryThumbs.params.control = galleryTop;

a working example of the problem is here: http://ift.tt/2fYrVQx

I didn't expect the result with loop: true, when I set it to false, the slider works great.

Does anyone have a solution for this?




jeudi 24 novembre 2016

Events bubbling down in Ember

In HTML element space, when a child and parent element has separate actions and when the child element is clicked, first the child action is invoked, and then the parent action is invoked.

However when the child is a Ember component, parent action is invoked first and then the child component action is invoked. Why is that difference in behaviour?

JSFiddles:

Case "parent and child are HTML elements"

Case "parent is HTML element and child in ember component"




Using JSON API response within Ember component

I have a component I'd like to use to create permalinks (hasherize) some titles for pages on a website CMS thingy I'm creating. I figure since I do this fairly often I should create a component so I can reuse it.

The component just listens to keystrokes on a text input, and uses an ajax call to fetch an API response that will (hopefully) return a single data record containing the permalink.

The component is not using a model because the permalink isn't a record or anything. I'm just using plain ajax utilizing the ember-ajax module. How do I deal with the somewhat 'complex' JSON API responses I'll be getting? Do I need to dig into them manually to get what I want? On a normal 200 response this isn't tough. Errors though, are a different story.

If so, how do I deal with errors? Let's say my permalink cannot be created for some reason (maybe it's a duplicate title and the permalink needs to be unique), I will get a 422 response, meaning it'll be an error object. How would I parse that into usable information?

Here is an example error response:

{
    "errors": [
         {
              "status":"422",
              "detail":"Error analyzing permalink: Permalink for 'test-page-title' already exists.",
              "source":{
                  "pointer":"data/attributes/permalink"
              }
         }
    ]
}

Is using a component for this even what I should be doing?




Ember.js ember-infinity plugin, how to work with multiple models?

here my beginig issue - http://ift.tt/2gF2Dbp

but i have some more trouble with it… My comments are in the child component. So i call it template like this:

And inside of it, i use:

if i change it to: Than i see request, but i get error "ember.debug.js:31321 TypeError: Cannot read property 'pushObjects' of undefined" It's because there no model.comments.comments.

How to solve this?




this.store.peekAll() and firstObject

Let's assume following code of route:

model() {
  return this.store.peekAll('user');
}

and simple template:



I would like to push that firstObject part into model because I always want to use only first record. With Ember objects it should be possible to use:

return this.store.peekAll('user').get('firstObject')

but this is not working because peekAll does not return Ember object in such way. What is the correct way of doing this?

[*] I'm using peekAll() instead of peekRecord() because peekRecord does not update when data in store are changed.




Deploy Ember client on tomcat (Eclipse)

I need to deploy an Ember client locally on a Tomcat server. I added a Tomcat server in eclipse, and associated my Ember client to it. Thus theoretically, when starting the server the client should be launched.

However, when i start the server i get a error 404 404 ”The requested resource is not available”.

Anyone here who have managed to deploy an Ember client on a Tomcat server? if so, could you kindly detail the steps that were taken in order to achieve this objective?

Thank you!




Append JSON elements in Ember

I am having an array with some of values (i.e., [1,2,3,4,5]), now i have to convert this array elements into JSON format.

I tries this one,

var Jsondata = {};
            for (i = 0; i < Response.get('firstname').length; i++) {
                Jsondata.push({
                    name : Response.get('firstname')[i]
                });
            }
 Ember.Logger.debug(Jsondata );

but it shows some error :

carousel.js:575 Uncaught TypeError: Jsondata.push is not a function(…)

how to append json elements in ember?




Ember 2.5 observe session property changes

I've monkey-patched my router to store the current route components in a session variable:

var Router = Ember.Router.extend({
    customSession: Ember.inject.service('session-custom'),
    location: config.locationType,

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

        this.get('customSession').set('currentEntity', this.get('currentRouteName').split('.')[0]);
        this.get('customSession').set('currentDetailView', this.get('currentRouteName').split('.')[1]);

    }
});

I know that this is not the cleanest of solutions, but writing the session to the console proves that at least those parameters are set.

In my controller, I'd like to listen for changes in these parameters, but somehow this does not work:

import Ember from 'ember';
import ApplicationController from './application';

export default ApplicationController.extend({

    customSession: Ember.inject.service('session-custom'),

    currentRouteNameChanged: Ember.observer('customSession.currentEntity', function () {
        console.log("route changed");
    })
});

i.e. "route changed" is never printed to the console.

This seems quite an easy fix, but I haven't been able to find a solution on SO.

Thanks!




Google Cloud Storage Bucket: XML error when reloading an Ember.js app in GCS

We recently moved an Ember.js app hosted in an Amazon AWS S3 bucket to a Google Cloud Storage Bucket. The app works great when we load the index.html page. Ember transitions work just fine however, when we directly visit a URL that isn't the project's main route (for example, /account-settings) or reload a URL that we are working on, we get the following error:

<Error>
    <Code>NoSuchKey</Code>
    <Message>The specified key does not exist.</Message>
</Error>

My assumption is that this has to do with the request not being handled by the Ember Router and index.html? I couldn't find any solutions to fix this in the Google Cloud documentation. How can I fix this?




Electron auto-update isn't working in emberjs

I try to implement auto-update from electron in emberjs, but the Examples aht docs does not work.

//const autoUpdater = requireNode('ember-electron').autoUpdater; //undefined
const autoUpdater = requireNode('auto-updater');
const appVersion = requireNode('./package.json').version;
//const os = require('os').platform();
//console.log('TEST');

autoUpdater.setFeedURL('http://localhost:80/updates/latest' + '?v=' + appVersion);

Do i somethink wrong with the reqire? I get this two errors:

Uncaught Error: Cannot find module 'auto-updater'

C:\dev\project\node_modules\electron-prebuilt\dist\resources\electron.asar\renderer\in…:113 Uncaught TypeError: Cannot read property 'listeners' of undefined




Can I build an application/website in PHP (specifically Silex), but have a dashboard in Ember for all the CRUD functionality?

I would like to build a blog in Silex, and have the dashboard in Ember. So the user interface would be PHP/Silex, but the admin interface would be Javascript/Ember. I haven't been able to find any examples. Any ideas?




ember-cli gives "Unexpected end of JSON input"

I have recent node (7.1.0) and npm (4.0.2) installations on macOS Sierra 10.12.1 with Xcode 8.1. The installation of the ember-cli package seems to work fine apart from two warnings:

08:51 $ npm install -g ember-cli
npm WARN deprecated node-uuid@1.4.7: use uuid module instead
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
/usr/local/bin/ember -> /usr/local/lib/node_modules/ember-cli/bin/ember
/usr/local/lib
└── ember-cli@2.9.1 

But when I call ember it always gives me the following error:

08:52 $ ember --help
module.js:593
    throw err;
    ^

SyntaxError: /Users/torstenkemps-benedix/package.json: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Object.Module._extensions..json (module.js:590:27)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.require (module.js:500:17)
    at require (internal/module.js:20:19)
    at Function.Project.getProjectRoot (/usr/local/lib/node_modules/ember-cli/lib/models/project.js:662:13)
    at module.exports (/usr/local/lib/node_modules/ember-cli/lib/cli/index.js:76:22)
    at /usr/local/lib/node_modules/ember-cli/bin/ember:27:3

How can I get ember to run correctly?




mercredi 23 novembre 2016

How to get Ember CLI to only recompile SASS when styles change?

I'm onboarding onto a project built using Ember. The project uses ember-cli-sass to watch and compile .scss files. The project is fairly large and componentized, with over 100 separate scss files. As a result, the ember-cli-build.js configuration looks like:

sassOptions: {
  includePaths: ['app']
}

The list is truncated a little bit, but the point is, the project has to include the /app path in its list of folders to watch in order to hear all the possible style changes.

This has two side effects. First, it makes for fairly slow SASS compiles. Second, SASS compiles occur when literally any file in the /app hierarchy changes, including javascript files.

Is there any way to configure ember-cli or ember-cli-sass to only compile on .scss changes?




Unwanted multiple passes thru broccoli-uglify-sourcemap

When I build my ember app, the uglify process seems to run 3x. I end up with the correct files in /dist (no duplicates) but I am trying to figure out what causes the multiple processing since it adds some 40+s to the entire build time. I am looking for help tracking down what causes this behavior. Any pointers/suggestions are appreciated! Below are the details from

  • build output
  • ember and npm version output
  • ember-cli-build.js
  • package.json dependencies

vagrant@web ~/sourcecode/ember-app (develop) $ DEBUG=broccoli-uglify* ember build -prod WARNING: WARNING: Node v6.1.0 has currently not been tested against Ember CLI and may result in unexpected behaviour. Could not start watchman; falling back to NodeWatcher for file system events. Visit http://ift.tt/22TlJJ7 for more info. ⠧ Building broccoli-uglify-sourcemap [starting]: assets/emberapp-new.js 3426.396KB +0ms broccoli-uglify-sourcemap [finsihed]: assets/emberapp-new.js 1972.914KB in 31858ms +32s [WARN] `assets/emberapp-new.js` took: 31858ms (more than 20,000ms) broccoli-uglify-sourcemap [starting]: assets/vendor.js 2919.476KB +186ms broccoli-uglify-sourcemap [finsihed]: assets/vendor.js 1055.143KB in 23658ms +24s [WARN] `assets/vendor.js` took: 23658ms (more than 20,000ms) broccoli-uglify-sourcemap [starting]: vendor/smart-app-banner/smart-app-banner-customized.js 18.722KB +81ms broccoli-uglify-sourcemap [finsihed]: vendor/smart-app-banner/smart-app-banner-customized.js 17.271KB in 195ms +195ms ⠧ Building broccoli-uglify-sourcemap [starting]: assets/emberapp-new.js 3426.396KB +5s broccoli-uglify-sourcemap [finsihed]: assets/emberapp-new.js 1972.914KB in 23366ms +23s [WARN] `assets/emberapp-new.js` took: 23366ms (more than 20,000ms) broccoli-uglify-sourcemap [starting]: assets/vendor.js 2919.476KB +299ms broccoli-uglify-sourcemap [finsihed]: assets/vendor.js 1055.143KB in 15446ms +15s broccoli-uglify-sourcemap [starting]: vendor/smart-app-banner/smart-app-banner-customized.js 18.722KB +56ms broccoli-uglify-sourcemap [finsihed]: vendor/smart-app-banner/smart-app-banner-customized.js 17.271KB in 144ms +144ms ⠏ Building broccoli-uglify-sourcemap [starting]: assets/emberapp-new.js 3426.396KB +6s broccoli-uglify-sourcemap [finsihed]: assets/emberapp-new.js 1972.914KB in 21768ms +22s [WARN] `assets/emberapp-new.js` took: 21768ms (more than 20,000ms) broccoli-uglify-sourcemap [starting]: assets/vendor.js 2919.476KB +73ms broccoli-uglify-sourcemap [finsihed]: assets/vendor.js 1055.143KB in 13516ms +14s broccoli-uglify-sourcemap [starting]: vendor/smart-app-banner/smart-app-banner-customized.js 18.722KB +46ms broccoli-uglify-sourcemap [finsihed]: vendor/smart-app-banner/smart-app-banner-customized.js 17.271KB in 118ms +118ms Built project successfully. Stored in "dist/". File sizes: - emberapp-new-386fe2160c8b66e54bf392d77ba05d77.js: 1.88 MB (237.26 KB gzipped) - emberapp-new-9b01fe5dd8aa1c1edd813ec6df1b770f.css: 228.16 KB (25.57 KB gzipped) - emberapp-new-blessed1-3993cdbb2f4c8271d7225ab60b2f499b.css: 441.35 KB (47.48 KB gzipped) - emberapp-new-blessed2-7ab46f5c0abdc702458f973a1104c1c6.css: 414.31 KB (38.13 KB gzipped) - emberapp-new.css: 1.07 MB (106.06 KB gzipped) - vendor-a88fcc2735e20663a1d61815d538e5be.js: 1.01 MB (260.19 KB gzipped) - vendor.css: 0 B - smart-app-banner-customized.js: 16.87 KB (6.3 KB gzipped) - smart-app-banner.css: 7.97 KB (1.64 KB gzipped)


Output from ember version --verbose && npm --version:

vagrant@web ~ $ ember version --verbose WARNING: WARNING: Node v6.1.0 has currently not been tested against Ember CLI and may result in unexpected behaviour. Could not start watchman; falling back to NodeWatcher for file system events. Visit http://ift.tt/22TlJJ7 for more info. ember-cli: 2.5.0 http_parser: 2.7.0 node: 6.1.0 v8: 5.0.71.35 uv: 1.9.0 zlib: 1.2.8 ares: 1.10.1-DEV icu: 56.1 modules: 48 openssl: 1.0.2h os: linux x64

vagrant@web ~ $ npm --version 3.8.6


ember-cli-build.js

var EmberApp = require('ember-cli/lib/broccoli/ember-app'),
bless = require('ember-cli-bless').blessCss,
postcss = require('broccoli-postcss'),
autoprefixer = require('autoprefixer'),
combineMq = require('broccoli-css-mqpacker'), // broccoli-combine-mq doesn't seem to work at this time (5/10/16)
mergeTrees = require('broccoli-merge-trees'),
funnel = require('broccoli-funnel'),
AssetRev = require('broccoli-asset-rev');

module.exports = function(defaults) {
// set options based on debug/test/prod env
var debug = EmberApp.env() === 'development',
    testing = EmberApp.env() === 'test',
    prod = !debug && !testing,
    sassOptions = debug ? { sourceMapEmbed: true } : { },
    autoprefixerEnabled = prod,
    postcssMap = debug ? { inline: true } : { },
    browsers = ["last 3 versions", "> 1%", "ie 8"],
    restOfApp,
    prefixed,
    revved;

// main ember app obj, will compile/minify css/js
var app = new EmberApp(defaults, {
        minifyCSS: {
            options: {
                processImport: false
            }
        },
  minifyJS: {
    enabled: true
  },
        bless: {
            enabled: false
        },
        fingerprint: {
            enabled: false
        },
        sassOptions: sassOptions,
        autoprefixer: {
            enabled: autoprefixerEnabled,
            browsers: browsers
        }
    });

var cssTree = funnel(app.toTree(), {
    include: ['assets/emberapp-new*.css']
});

if (debug) {
    prefixed = postcss(cssTree, {
        plugins: [{
            module: autoprefixer,
            options: {
                browsers: browsers
            }
        }],
        map: postcssMap
    });

    // get other dist files (besides main.css)
    restOfApp = funnel(app.toTree(), {
        exclude: ['assets/emberapp-new*.css']
    });
}

if (prod) {
    prefixed = cssTree;

    // get dist files we AREN'T messing with (this includes a copy of main.css)
    restOfApp = funnel(app.toTree(), {
        exclude: ['assets/**/*.js', 'index.html']
    });

    // combine media queries
    var combined = combineMq(prefixed, {
        files: ['*.css'],
        settings: {
            beautify: true
        }
    });

    // bless
    var blessed = bless(combined, {
        imports: true
    });

    // get all files we want to rev, plus index.html
    var blessedAndIndex = mergeTrees([
        funnel(app.toTree(), {
            include: ['index.html', 'assets/**/*.js', 'assets/**/.css']
        }),
        blessed
    ]);

    // asset rev
    revved = new AssetRev(blessedAndIndex, {
        extensions: ['css', 'js']
    });
}

app.import('bower_components/jquery/dist/jquery.min.js');
app.import('bower_components/moment/min/moment.min.js');
app.import('bower_components/moment-timezone/builds/moment-timezone-with-data.min.js');
app.import('vendor/modernizr.custom.98851.js');
app.import('vendor/jquery.cookie.js');
app.import('vendor/jquery.touchSwipe.min.js');
app.import('vendor/simplebar/simplebar.min.js');
app.import('vendor/jquery-plugins.js');

if (prod) { // prod
    return mergeTrees([restOfApp, revved], {
        overwrite: true
    });
} else if (testing) { // test
    return app.toTree();
} else { // development
    return mergeTrees([restOfApp, prefixed], {
        overwrite: true
    });
}
};


dependencies from package.json

"autoprefixer": "^6.3.6",
"bower": "^1.7.9",
"broccoli-asset-rev": "^2.4.2",
"broccoli-combine-mq": "^1.0.3",
"broccoli-css-mqpacker": "^0.2.1",
"broccoli-funnel": "^1.0.1",
"broccoli-merge-trees": "^1.1.1",
"broccoli-postcss": "^3.0.0",
"ember-ajax": "0.7.1",
"ember-cli": "^2.5.0",
"ember-cli-app-version": "^1.0.0",
"ember-cli-autoprefixer": "0.6.0",
"ember-cli-babel": "^5.1.6",
"ember-cli-bless": "0.1.1",
"ember-cli-dependency-checker": "^1.2.0",
"ember-cli-htmlbars": "^1.0.3",
"ember-cli-htmlbars-inline-precompile": "^0.3.1",
"ember-cli-inject-live-reload": "^1.4.0",
"ember-cli-jshint": "^1.0.0",
"ember-cli-qunit": "^1.4.0",
"ember-cli-release": "0.2.8",
"ember-cli-sass": "5.3.1",
"ember-cli-uglify": "^1.2.0",
"ember-data": "^2.5.0",
"ember-export-application-global": "^1.0.5",
"ember-load-initializers": "^0.5.1",
"ember-resolver": "^2.0.3",
"loader.js": "^4.0.1"




Where to install Facebook's Watchman for Ember.js on Ubuntu?

I apologize for the noob question but...

I've installed watchman from source from their docs but where do I put this folder so that ember-cli can use it?




Emberjs How to access an class without creating a model

Hy there.

Is there a way to access a model class without creating a record from store and looking at his constructor ?

I have :

const feedback = this.store
                     .createRecord('feedback')
                     .get('constructor');
const attrs    = Ember.get(feedback, 'attributes')
                      ._keys
                      .list;
// attr = ["attr_1", "attr_2", ...]

Is there a proper way to find the same result without creating a record ?

cheerz




Ember-validation how to implement lazy validation

I am using ember-cli:2.5.0 and ember-validations:v2.0.0-alpha.5 In my ember-component i have a validation which is running automatically for each change in a attribute but i want to run this validation only if i call "validate()" method in technical term call validation lazily.

Please find the below code samples,

import Ember from 'ember';
import EmberValidations, { validator } from 'ember-validations';

export default Ember.Component.extend(EmberValidations, {

_bookModel(data = {}) {
return Ember.Object.extend(EmberValidations, {
  bookVersion: null,
  isEditable: false,
  validations: {
    bookVersion: {
      inline: validator(function() {
        var version = this.model.get('bookVersion') || "",
          message = [];

         if (Ember.isEmpty(bookVersion)) {
           message.push("Book Version is mandatory!!!");
         }

        if (message.length > 0) {
          return message.join(',');
        }
      })
    }
  }
}, data);
}

});

I want the above validation to run only calling "this.get('newBook').validate()". I am entirely new to ember so down-voter please put your comments before down-voting for other kindly let me know for any more code samples.

Your help should be appreciable.




I am unable to see he coverage statistics of my javascript module with sonarqube-gradle-plugin

Problem: I am unable to see he coverage statistics of my javascript module with sonarqube-gradle-plugin

Project Background I have a multi module project being built with Gradle. I am using java as backend language and ember.js as Frontend language. I am trying to integrate Sonar for code coverage of both the codes.

I am using sonarqube gradle plugin 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.2' for sonar coverage.

Below is my sonar.properties

sonar.projectName=myproject
sonar.projectKey=com.ideas.myproject:myproject

sonar.modules=module-ui,module-services

sonar.sourceEncoding=UTF-8
sonar.projectBaseDir=myproject

module-ui.sonar.projectBaseDir=module-ui
module-ui.sonar.sources= module-ui
module-ui.sonar.language=js
module-ui.sonar.tests=tests
module-ui.sonar.javascript.coveragePlugin=lcov
module-ui.sonar.dynamicAnalysis=reuseReports
module-ui.sonar.javascript.lcov.reportPath=build/coverage/lcov.info
module-ui.sonar.javascript.jstestdriver.reportsPath=tests/reportfile.xml

module-services.sonar.projectBaseDir= module-services
module-services.sonar.sources=/src/main
module-services.sonar.language=java
module-services.sonar.java.coveragePlugin=jacoco
module-services.sonar.jacoco.reportPath=/build/jacoco/test.exec

Details: I am using the ember-cli—code-coverage plugin which generates the lcov report . I would want sonar to read the lcov report and show the coverage statistics on sonar.

The javascript plugin is installed on Sonar Server.

I tried to follow various answers to related questions on stack overflow but couldn’t find any success as yet.

Issue: I can see the sonarcoverage of java module on CI but not for the JS module. enter image description here

One observation: I cannot see any LCOvSensor in the debug log. What am I Missing? Please help.




Define transitionTo in Emberjs component

I've a component which is being used at several routes. Now in that component I want to using swipeLeft and swipeRight events from ember-gestures library.

When i try alert messages they get fired on both events. But when I try to run this.transitionTo('someRoute', dynamicPart) then it doesn't get fired.

I get Uncaught TypeError: this.transitionTo is not a function(…) error.

How can I use transitionTo() from Ember-component?




mardi 22 novembre 2016

how to configure Azure documentDB in emberjs application

I am new to emberjs,I have to create simple application using ember js which can interact with azure documentDB(i.e. load,create and modify records serving on azure document DB).Please help me on how to configure documentDB with ember application.

Thanks




How to make a conditional link-to in Ember.js?

I am using Ember.js version 2.8.2.

I want to wrap things inside link-to only if condition is true.

First try:


  
    contents here
  
  
    contents here


Problem: the code is not dry, because content repeats twice.

How should I do this? Thanks.




Getting error when upgrading from ember-data 2.5 to 2.8

  • ember-data@2.5.3 to ember-data@2.9.0
  • ember@2.4.1 to ember@2.8.3

The following worked fine before the update, it appears that ember-data is causing the issue.

Getting the following error: Uncaught TypeError: Cannot read property 'eachAttribute' of undefined

I am reloading a model this.modelFor('admin').get('ssoApplicationSubscriptions').reload();

When it starts executing the eachAttribute loop I get the error. Interestingly the constructor is undefined at this point.

enter image description here

Here are the model definitions

// Organisation
export default DS.Model.extend({
  name: attr('string')
});

// Institution Organisation
export default Organisation.extend({
  ssoApplicationSubscriptions: hasMany('sso-application-subscription', { polymorphic: true })
});

I am using the JSONAPIAdapter/Serializer.




EmberJS retrieve current user from ember-simple-auth authenticator

Issue:

I am trying to retrieve the current user logged in from ember-simple-auth by extending ember-simple-auth/authenticators/base. I just want to create a function called currentUser() that will return the username but I get the error whenever I try calling the function:

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

Attempt:

the function currentUser() is defined below:

// app/authenticators/oauth2.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';

const RSVP = Ember.RSVP;

export default Base.extend({
  restore() {
      // restore user session
  },
  currentUser() {
      return this.get("username");
  }),
  authenticate(username, password) {
    this.set('username', username);
    return new RSVP.Promise((resolve, reject) => {
      Ember.$.ajax({
        url: config.baseURL + "accounts/login",
        data: {
          username: username,
          password: password
        },
        type: 'POST',
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        complete: (response)=> {
          if (response.responseJSON.isAuthenticated)
            resolve({isAuthenticated: true});
          else
            reject("Wrong credentials.");
        }
      });
    });
  },
  invalidate() {
    // log out
  }
});

I called the function using:

// app/controllers/application.js
import Ember from 'ember';

export default Ember.Controller.extend({
  session: Ember.inject.service('session'),

  actions: {
    alertSession() {
      console.log("!! " + this.get('session').currentUser());
    },
    invalidateSession() {
      this.get('session').invalidate();
      this.transitionToRoute('login');
    }
  }
});

this.get('session').invalidate(); works, but this.get('session').currentUser(); will return the error mentioned above. Please let me know how to fix this. Also, I am using Ember 2.5.1.

Thanks!




Ember: Paginating sorted/searched hasMany relationship on single-page application

I am working on a single-page application wherein I have to page a hasMany relationship based on sort and search criteria. The back-end is straightforward but the front-end is giving me troubles. I suspect the problem is architectural and wondered if anyone had any ideas.

Here’s the scenario: You bring up the application and it queries for a list of regions. You select a region, and then query for its hasMany locations. We didn’t used to paginate locations so this was straightforward and you could get them with sideloading. Now we have a requirement to support thousands of locations, so now we fire off a query that supports pagination, with page, perPage, and sort or search params. The backend is fine. The problem is in the front end, getting this working with a pagination widget.

I am trying to use ember-cli-pagination for the pagination widget. It requires a dedicated Controller (actually ArrayController, deprecated) and a dedicated Route for the model. I would be happy to use something else if something else would work.

The models:



Region = DS.Model.extend
    …
    locations: DS.hasMany 'location', async: true, inverse: null






    Location = DS.Model.extend
        …
        region: DS.belongsTo 'region', async: true, inverse: null


The locations are displayed in a component called ‘store-scorecard’, which is specified on index.hbs:



    


and here is within the component. You can see the locations are specified here and the ember-cli-pagination component is included with the page-numbers element.



    
        
    
    ...
    
        
    


There is one route and one controller, the IndexRoute and IndexController. The locations query had always been done from within the store-scorecard component, i.e.,



    StoreScorecardComponent = Ember.Component.extend
        ...
        locations: Ember.computed 'area', 'region', ->
            lowestRegion = @get('lowestRegion')
            lowestRegion.get 'locations'
        lowestRegion: Ember.computed 'area', 'region', ->
            @get('area') || @get('region')
        hasPagedLocations: Ember.computed 'locations.[]', ->
            @get('locations.length') > 0


I modified it to do the query in the component using a dedicated injected controller:



    StoreScorecardComponent = Ember.Component.extend
        store: Ember.inject.service()
        locationsIndexController: Ember.inject.controller('locations.index')
        ...
        locations: Ember.computed 'area', 'region', ->
            @get('store').query('location',
                region_id: @get('lowestRegion.id')
                page: @get('locationsIndexController.page')
                per_page: @get('locationsIndexController.perPage')


This runs the right query if you hard-code it (e.g., specify page: 1, per_page: 7), but because the locationsIndexController has no data, it can't construct the right query from controller data. The ember-cli-paginator component never gets its data and just as importantly, it doesn't set the page or totalPages values on the controller.

I have the same problem whether I make it a LocationsController or a LocationsIndexController or a RegionLocationsController (with corresponding routes). When I create these, we never hit that code. The LocationIndexController never has data, even hard-coded data. If I take the query out of the component and put it in the dedicated route (e.g., LocationsIndexRoute), we never hit that route so it never makes the query. So how should I set up this architecture, and how should I ensure that the right route and controller get used for the hasMany relationship?

Thanks in advance.




¿how to watch less styles in a pod structure using ember?

im facing an issue when moving my less files to a pod structure outside the styles folder.

im trying to put i.e:

pods/user/register/style.less

pods/components/app-login/styles

and import them from my styles/app.less file.

but so far it just compiles for the first time, but does not watch for future changes. I tried to create a symlink inside my styles folder to pods folder but sometimes works and sometimes breaks broccoli compilation so i declined.

¿Do you have a better workaround for this? For the moment im going back to the old structure




How can I dynamically change validator options after creating in ember-cp-validations?

I need to change 'presence' option from 'true' to 'false' depending on dynamic form state. If formState == 'a' 'name' field is required, if == 'b' then not, and if I dynamically toggled formState, validator should change its option.

I tried do that, but it didn't help:

//form/component.js 
init() {
    this._super(...arguments);

    const Validations = buildValidations({
        name: validator('presence', {
        presence: Ember.computed('formState', function() {
            return this.get('formState') == 'a';
        })
     }),
    });

    // I use ember-validated-form-buffer for buffering changes
    this.set('formValues', formBufferProperty('model', Validations));
}

Is there any way to solve it?




How to find value of computed property of a component from javascript console(chrome/firefox console) in emberjs?

How can I find the following values in Emberjs from console:

  1. Value of Computed Property of some component
  2. Value of a Service

I know it is possible with the use of __container__ but I'm not able to find it in documentation or any other forum.

Since we are not using ember-data and are actually using several custom services(e.g. data, ajax, session,...) this has become essential for us to find some way to get the value of computed property and service from console.




Ember.js 2.9 simple nested routes error on full page reload

I am a beginner to Ember.js so I took the Codeschool course 'Try Ember'. So following this course I actually get an error.

My router.js file looks like this:

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

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

Router.map(function() {
  this.route('orders', function(){
    this.route('order', {path: '/:order_id'});
  });

});

export default Router;

Now as far as I understand from the tutorial I have two routes orders.js and order.js with templates templates/orders.hbs and templates/orders/order.hbs respectively.

orders.js file:

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return [
      { id: '1', name: 'Vlatko'},
      { id: '2', name: 'Mila'}
    ];
  }
});

order.js file:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params){
    return [
      { id: '1', name: 'Vlatko'},
      { id: '2', name: 'Mila'}
    ].findBy('id', params.order_id);
  }
});

templates/orders.hbs file:

<h2>Hello from orders</h2>


  <p>
    
      Order 
    
  </p>




templates/orders/order.hbs file:

<p>Order  for </p>

So everything is pretty simple and works well, but when I try to do a full page reload(enter directly on the page) /orders/1 it raises two errors Error while processing route: orders.order No model was found for 'order' Error: No model was found for 'order' and Error: No model was found for 'order' . Now, I've searched a lot on the web and I can't find the same error.

An additional hint: This only happens when I use nested routes. If for instance I have something like this in my router.js:

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

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

Router.map(function() {
  this.route('orders');
  this.route('order', {path: '/orders/:order_id'});
});

export default Router;

I get not error. If this question has been asked before please don't downvote me and just point me to the answer and I will gladly delete it.




How to include d3.js v4 in ember.js app?

I installed d3.js via npm. Now when I import a d3 module for example:

import {scaleLinear} from "d3-scale";

I'm getting the error Could not find the module d3-scale. Is it not the correct way to import?




Ember - creating new child route not displaying its new template

I have a single route in my app right now and am trying to create a new one as a child of that.

Existing code which works:

app.js

app.Router.map(function(){
   this.resource('home', {path:''},function(){
     this.route('search', {path:'/home/search'})
   })
})

File structure

-app
  -route
    - home-route.js
    - home-search-route.js

  -controller
    - home-controller.js
    - home-search-controller.js

  -template
    - home
       - search.ehbs
    - application.ehbs
    - home.ehbs

The above works fine and i can access my url at http://localhost/home/search. The application.ehbs and home.ehbs, both of them have in them. Now when i define a new route, which i want as a child of search, this thing doesn't seem to work. New code and file structure below:

app.js - with new route

app.Router.map(function(){
   this.resource('home', {path:''},function(){
     this.route('search', {path:'/home/search'}, function(){
        this.route('result', {path:'/result'})
     })
   })
})

file structure - with new template

-app
  -route
    - home-route.js
    - home-search-route.js
    - home-search-result-route.js

  -controller
    - home-controller.js
    - home-search-controller.js

  -template
    - home
       - search.ehbs
       - search
          - result.ehbs 
    - application.ehbs
    - home.ehbs

I move to this new route (result.ehbs) on a button click, which is defined in a action in "home-search-controller.js" as

this.transitionToRoute('home.search.result')

So, when i click the button, the url changes to http://localhost/home/search/result and i see the new route "home-search-result-route.js" is also hit (consoling values from there), but it doesnt shows the result.ehbs, it just stays on search.ehbs. Any idea, what could be going wrong.

I read several posts, and matched the structure and it seems right to me. And i also checked with Ember inspector, the file names it shows there matches with what i have defined.




Ember, #if item.value inside #each, when value changed, the page did not update

   setupController: function(controller, model) {
      controller.set('testItem', [
        Em.Object.create({name: 'aaa', hilight: false}),
        Em.Object.create({name: 'BBB', hilight: true}),
        Em.Object.create({name: 'ccc', hilight: false})
      ]);
    },

I set setupController in the route.

 changeTest: function(item){
    item.hilight = !item.hilight;
 },

And this action in the controller. The handlebar code is like this:


    
        <div>
            <h4></h1>
        </div>
    
        <div>
            <i></i>
        </div>
    
    <button ></button>


The action function is executed successfully when I click the action, but page could not be updated.

So, what is the problem?




lundi 21 novembre 2016

git emberjs/rails - Best practice for pushing both frameworks up to a single repo

I just started building a rails/ember app and it's the first time i'm using two different frameworks with a single app. I was wondering whats the best practical way to manage version control? I currently have a local repository for each framework ( 1 for ember and 1 for rails). I am pushing up to two separate branches to a single repository on github. masterRails for the rails side and masterEmber for Ember.

Thanks for the advice!!




How scalable is ember.js?

If i open 10 to 15 tabs at a moment how much memory will an ember/angular/react app consume compared to a webpage using jsp,php,etc?
Will moving to a client side framework pose anyother scalability problems in general?




Ember pass callback to service - undefined this

I have a service to upload many large files in chunks

export default Ember.Service.extend({
  run(files, callbacks) {
    // ugly async FileReader and ajax
    // calling callbacks during the process
  }
})

I need a bunch of callbacks to show progress, but the problem is that this in undefined within these callbacks

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

  didInsertElement() {
    // bind fileinput change event to set up pending files
  },

  ondonesingle(self, file, uuid) {
    // this is undefined
    // self is real this
  },

  actions: {
    submit() {
      let callbacks = {
        ondoneall: this.ondoneall,
        ondonesingle: this.ondonesingle,
        onprogressall: this.onprogressall,
        onprogresssingle: this.onprogresssingle,
        onerror: this.onerror,
        object: this // will be passed as first argument to each callback
      };
      this.get('upload').run(this.get('pending_files'), callbacks);
    },
  }
})

To work around this I have to carry reference to this everywhere.

It works, but it feels terribly wrong. What is the best practice to do this in Ember? Observable property also feels wrong, how would I observe progress of 2000 files? Put everything in one big object and share it across the app?




Error: GET http://localhost:4200/assets/vendor.js net::ERR_INVALID_CHUNKED_ENCODING, on Ember.js server

I am just getting started with Ember.js at v2.9.0, followed the tutorial on their page http://ift.tt/2fVWbt4, all good, save for one detail: Whenever I tried to refresh or load the development web app on Chrome browser after executing ember server on the cmd, the app would not load in browser and provide the following error most of the time (there were other errors as well but seem to be related to this one):

GET http://localhost:4200/assets/vendor.js net::ERR_INVALID_CHUNKED_ENCODING

, and one of the related errors is:

Uncaught ReferenceError: define is not defined at application.js:1

I have searched for this specific error but without luck, I tried some fix hints found, such as clearing some persistent data with the netsh command, doing an npm cache clean bower cache clean, deleting the node_modules and the bower_components folders and reinstalling dependencies; also ensuring that there was no weird proxy configuration in my LAN settings, etc.

I have encountered this error while following the tutorial, and it would kind of be bypassed by refreshing the browser a few times until the app displayed. That was before, but now the refresh does not work when working on an existing application.

I am on:

Windows 10

ember-cli v.2.9.1

node.js LTS v.6.9.1

I need to get going with this rather soon, so any hint to resolve this issue is appreaciated. Thanks!




Json Api Serializer Doesn't Work with Rails

I want to use Rails as an API only backend for EmberJS. I have heard json-api serializer has some advantages over active_model_serializer. So, i wanted to give it a try but that doesn't seem to work.

App is all about this;

rails-api new ShopApp 
rails g scaffold Product name price

Added 2 seed data & json-api serializer gem in gemfile

app/db/seeds.rb

Product.create(name:"House",price:"14687640")
Product.create(name:"Car", price:" 12345")

app/Gemfile

gem 'jsonapi-serializers'
gem 'rails-api'

I, manually have added app/serializers directory and in there app/serializers/product_serializer.rb

#app/serializers/product_serializer.rb
require 'jsonapi-serializers'

class ProductSerializer
  include JSONAPI::Serializer
  attribute :name
  attribute :price
end
JSONAPI::Serializer.serialize(products, is_collection: true)

I start rails server, and it gives me json data that includes created_at & updated_at.What might be the problem, i have gone trough documentation on github but everything seems to be alright.Please help and thank you ^.^




Ember 1.12 does not work on IE11

I upgraded my Ember 1.8 webapp to Ember 1.12. On 1.8 it worked on all browsers, on 1.12 it does not work anymore on IE11. I get SCRIPT1014 (invalid character) on:

 let CONTAINER = `__${new Date()}_container`;

And I get SCRIPT5009 (define is not defined) on:

 define('xxx/adapters/yyy', ['exports', 'xxx/adapters/base/zzz-adapter'], function (exports, zzz) {

Upgrading to Ember 1.13 is not an option on the short term. Anyone else having problems with Ember 1.12 and IE11?




Ember server showing error - The Broccoli Plugin: [object Object] failed with

I'm new to Ember js and created a sandbox app. Every time I run ember s in my terminal (I'm on Ubuntu 16.04) I get these errors and warnings:

WARNING: Node v7.0.0 has currently not been tested against Ember CLI and may result in unexpected behaviour.
Could not start watchman; falling back to NodeWatcher for file system events.
Visit http://ift.tt/22TlJJ7 for more info.

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

File: /home/lykos/code/sandbox/app
The Broccoli Plugin: [object Object] failed with:
Error: watch /home/lykos/code/sandbox/app ENOSPC
    at exports._errnoException (util.js:1026:11)
    at FSWatcher.start (fs.js:1297:19)
    at Object.fs.watch (fs.js:1322:11)
    at FSMonitor._measure (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/heimdalljs-fs-monitor/index.js:66:21)
    at Object.watch (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/heimdalljs-fs-monitor/index.js:82:30)
    at NodeWatcher.watchdir (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/sane/src/node_watcher.js:144:20)
    at new NodeWatcher (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/sane/src/node_watcher.js:45:8)
    at new sane (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/sane/index.js:17:12)
    at Watcher_addWatchDir [as addWatchDir] (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/ember-cli-broccoli-sane-watcher/index.js:131:17)
    at /home/lykos/code/sandbox/node_modules/ember-cli/node_modules/broccoli-builder/lib/builder.js:93:35

The broccoli plugin was instantiated at:
    at WatchedDir.Directory (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/broccoli-source/index.js:14:31)
    at new WatchedDir (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/broccoli-source/index.js:58:13)
    at EmberApp._initOptions (/home/lykos/code/sandbox/node_modules/ember-cli/lib/broccoli/ember-app.js:200:17)
    at new EmberApp (/home/lykos/code/sandbox/node_modules/ember-cli/lib/broccoli/ember-app.js:121:8)
    at module.exports (/home/lykos/code/sandbox/ember-cli-build.js:6:13)
    at Class.setupBroccoliBuilder (/home/lykos/code/sandbox/node_modules/ember-cli/lib/models/builder.js:70:19)
    at Class.init (/home/lykos/code/sandbox/node_modules/ember-cli/lib/models/builder.js:50:10)
    at Class.superWrapper [as init] (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/core-object/lib/assign-properties.js:32:18)
    at Class (/home/lykos/code/sandbox/node_modules/ember-cli/node_modules/core-object/core-object.js:32:33)
    at Class.run (/home/lykos/code/sandbox/node_modules/ember-cli/lib/tasks/serve.js:15:19)

Livereload server on http://localhost:49152
Serving on http://localhost:4200/

And this is my package.json file

{
  "name": "sandbox",
  "version": "0.0.0",
  "description": "Small description for sandbox goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.12.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^2.4.1",
    "ember-cli": "2.9.1",
    "ember-cli-app-version": "^2.0.0",
    "ember-cli-babel": "^5.1.7",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-htmlbars": "^1.0.10",
    "ember-cli-htmlbars-inline-precompile": "^0.3.3",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-jshint": "^1.0.4",
    "ember-cli-qunit": "^3.0.1",
    "ember-cli-release": "^0.2.9",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^1.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "^2.9.0",
    "ember-export-application-global": "^1.0.5",
    "ember-load-initializers": "^0.5.1",
    "ember-resolver": "^2.0.3",
    "ember-welcome-page": "^1.0.3",
    "loader.js": "^4.0.10"
  }
}

I did a search and found this ember cli application build fails: The Broccoli Plugin: [object Object] failed with: but didn't work, I'm not sure if its related to some previous version - I've installed ember 2.9.0.

How can I fix this?