mardi 31 mai 2016

Create a controller event listened to by a component

I'm playing with ideas for making a drag and drop interface. I have multiple components that can be dragged into position over a grid. I will have a button that will allow the user to select different arrangements.

I want a function on the component that sets its position (quite simply with left and top). I want to be able to call this function when the component is inserted, and when a different arrangement is selected.

What I want to do is create an event in the route's controller. I then want each component to be able to listen for the event, and react as necessary. I'm afraid I don't understand enough to make this work. I've read the API, and a couple of questions on here (1, 2), but no luck.

Here's what I have...

The route's controller:

import Ember from 'ember';    
export default Ember.Controller.extend(Ember.Evented, {
    actions: {

        callPosition: function(){
            this.trigger('position');
            console.log('Trigger set...');
        },
})

And the component:

import Ember from 'ember';
export default Ember.Component.extend(Ember.Evented, {

    didInsertElement : function(){
        this.get('controller').on('position', this, this.position);
    },

    position: function(){
        console.log('event heard by the component');
    },

A few things I don't understand:

  1. Have I added the Ember.Evented mixin correctly?
  2. I've added the listener in the didInsetElement event as per the example. Is this the correct way to ensure the component will listen for the event throughout its lifetime?
  3. What's the scope of the event? Can it only be listened for so long at we 'get' the controller that set it?

Your advice is a great help to this budding amateur!




Having nested promises and returning them in route won't update the route model and the template using that model

in my route model i need to send two requests (previous and latest) and on the response i grab their ids to send two other requests(baslineCpature and currentcapture). when i got the responses of both requests, i need to send two other requests(fiberHealthData, wavelengthsPerSectionData). ember model should return (baslineCpature,currentcapture, fiberHealthData, wavelengthsPerSectionData ). one issue i have here is that i want to update my template as soon as i get response for baslineCpature and currentcapture.

Here is my code. I appreciate if someone can tell me what i am doing wrong.

model: function (params,transition) {

  var promiseA=null;
  var promiseB=null;
  var promiseA1=null;
  var promiseB1=null;

  promiseA1 = Ember.RSVP.hash({
    latest:this.store.findAll('latest'),
    previous: this.store.findAll('previous'),
  });

  promiseA= promiseA1.then((promiseAResolved) => {
    return Ember.RSVP.hash({
      baselineCapture:self.store.find('capture', promiseAResolved.previous.get('firstObject.id')),
      currentCapture: self.store.find('capture', promiseAResolved.latest.get('firstObject.id')),
    });
  });

  promiseB= promiseA.then((promiseAResolved) => {
    baselineId =  promiseAResolved.baselineCapture.id;
    currentId =  promiseAResolved.currentCapture.id;

    return Ember.RSVP.hash({
      fiberHealthData:self.store.findAll('fiber-health',{ adapterOptions: {current: currentId, baseline: baselineId}}),
      wavelengthsPerSectionData:self.store.findAll('wavelengths-per-section',{ adapterOptions: {current: currentId, baseline: baselineId}} )
    });
  });

//this should be retun of my model
  return Ember.RSVP.hash({
    baselineCapture:promiseA.baselineCapture,
    currentCapture:promiseA.currentCapture,
     fiberHealthData:promiseB.fiberHealthData,
    wavelengthsPerSectionData:promiseB.wavelengthsPerSectionData,
  });
}



ember frost tabs not displaying

I have installed ember-frost-tabs

I have pasted the code in the example here - http://ift.tt/1PfaV5I into the relevant pages.

I do not see anything. no tabs or text displays where the tabs should. If I removed the tabs and put 'abc' - dummy text in, this displays. So don't think there's anything wrong with my page.

Template (templates/cakes/lemonsponge.hbs):



  tab 1


  tab 2


  tab 3



Controller (controllers/cakes/lemonsponge.js):

import Ember from 'ember'

export default Ember.Controller.extend({
  queryParams: ['selectedTab'],

  selectedTab: 'controller',

  actions: {
    tabSelected (tab) {
      this.set('selectedTab', tab)
    }
  }
})

Route (routes/cakes/lemonsponge.js):

import Ember from 'ember'

export default Ember.Route.extend({
  queryParams: {
    selectedTab: {
      as: 'tab'
    }
  }
})

I just get a blank template displayed though.




Project broken by unidentified subdependency: how to recover? How to `npm install` with all packages limited by a date?

My project is successfully deployed via CI and working fine. But when I build it from the same commit locally, the project freezes without any error message. It's a huge Ember app with an enormous pipeline, and I've exhausted all my debugging ideas.

My only guess so far is that an npm subdependency update has broken something. I don't know which package is to blame. :(

I have no npm-shrinkwrap.json. I tried to introduce shrinkwrapping to the team, but it was causing too much trouble, so we went back to not using it.

No other team member has an up to date version of the project locally, so I don't have anyone to ask for a fresh npm-shrinkwrap.json.

I know the date at which the project was building correctly.

How do I tell npm to install every package (including subdependencies) limited by a date (in addition to restrictions specified in package.json files)?

If I were able to do that, I could see if the project starts working again. If it does, I could shrinkwrap and identify the troublesome package.

Any other suggestions to recover from this failure are also very welcome.

PS I'm using NVM, so I've tried both npm v2 and v3 -- same result.




Ember computed equal not working with ember-mirage

I'm trying to split products into two categories, snack and share, but my computed.equal isn't working. I don't have a database connected at the moment, so I'm using ember-mirage to fake the data. The products show on the page if I remove the if statement, but for some reason don't when I add the if statement. Thanks in advance.

products.hbs

   <div class='container'>
        
            
                <div class='col-md-4'>
                    <img src="">
                    <h3></h3>
                    <p></p>
                    <h4>£</h4>
                    <button type='button' class='btn btn-xs'>ADD TO BASKET</button>
                </div>
            
        
    </div>

model/product.js

export default Model.extend({

name: attr('string'),
description: attr('string'),
typeOf: attr('string'),
price: attr('number'),
image: attr('string'),

isSnack: Ember.computed.equal('typeOf', 'snack'),

isShare: Ember.computed.equal('typeOf', 'share')

});

mirage/config.js

this.get('/products', function() {
  return { 
    data: [{
      type: 'products',
      id:1,
      attributes: {
        name: "Mediterranean Snack Pop's",
        typeOf: 'snack',
        description: '',
        price: 0.80,
        image: ''
      }
    }, {
      type: 'products',
      id:2,
      attributes: {
        name: "Spicy Snack Pop's",
        typeOf: 'share',
        description: '',
        price: 0.80,
        image: ''
      }
    }
  }]
 };
});




Ember: Return a value or set a model property from Ember promise

If I have a promise, is it possible to return a value from it?

let itemData = [];
model.data.get('products').then(relatedItems => {
  relatedItems.forEach(function(item,index) {
    console.log(item.get('name')); // Product 1, Product 2 etc
    itemData.pushObject(item);
  });
},reject => {
  console.log('error '+reject);
});

If I try and return the itemData array after the promise has resolved I get undefined.

Alternatively (and preferably) I'd like to be able to set a model property when the promise has resolved:

// component code 

itemData:null,
init() {
  let model = this.get('data);
  model.data.get('products').then(relatedItems => {
     relatedItems.forEach(function(item,index) {
        this.set('itemData,item);
     });
  },reject => {
     console.log('error');
  });
}

The reason for all of this is that I need to sort the product items which I can only access via the promise (in this example). Having set the itemData property I was intending to do something like:

sortedItems:computed.sort('itemData','sortProperties'),
sortProperties:['name:desc']




Multiple actions in ember-i18n

I have a string used with ember-i18n which should contain 2 actions. The text in english is By clicking Signup you agree to our Terms and Privacy Policy and I need to add two links, one on Terms and the other on Privacy Policy. That text is also translated in other 9 languages and obviously the linkable part can be in different places of the string.

The link should be handled by an action in my controller that show a liquid-fire modal.

// controller/signup.js
export default Ember.Controller.extend({
    actions: {
        viewTerms() {
            this.set("showTermsPopup", true);
        }
    }
})

// router.js
...
this.modal("terms-modal", {
    withParams: ["showTermsPopup"],
    controller: "signup",
    otherParams: ["termsStmt"]
});
...

// templates/signup.hbs
...
  //translated text with actions
...

The result I'd like to have is as I write in the template

By clicking Signup you agree to our <a >Terms</a> and <a >Privacy Policy</a>

Any suggestion on how to implement that is welcome.

Versions: ember-cli: 2.5.1 ember.js: ~2.5.0 ember-i18n: 4.2.1




lundi 30 mai 2016

Pushing new date to ember javascript array

I am creating a basic ember app with javascript object arrays(Don't want to use anything else until I get a firm grasp). I am having trouble implementing functionality to add new users. I'm not sure what to add to my controller.

In the template:

<form > 

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

My students route: import Ember from 'ember';

 var students = [{
  id: 1,
  name: 'John',

}, {
  id: 2,
  name: 'Vanessa'     
}];

export default Ember.Route.extend({
  model() {
    return students;
  }
});




How to debug "Could not find module" in Ember.js acceptance tests?

I'm in the process of updating a project to Ember 2.5.0 but stumbled upon an obstacle with running the acceptance tests: after trying to import moduleForAcceptance following the documentation for 2.5.0, I'm getting the error

Could not find module timelines-front/tests/helpers/module-for-acceptance imported from timelines-front/tests/acceptance/create-note-test

The import line is a straight from the documentation:

import moduleForAcceptance from 'timelines-front/tests/helpers/module-for-acceptance';

I tried creating a new Ember project with one test route and an acceptance test, all generated with CLI, and the import works as expected, so I'm assuming that there's something in my app or test code that is messing up with the import statement.

Trying to isolate the case I tried the following after ember new without success in reproducing the error:

  • Copying package.json, bower.json and installing.
  • Comparing testem.json to testem.js.
  • Checking my Phantomjs version (running 2.1.1)
  • Copying Brocfile.js and disabling ember-cli-build.js

My question is: how can I debug the include path and / or find what in the app code is changing it and ruining the import?




ember modal dialog liquid fire

I am new to ember. Have use liquid fire to slide between pages. But would like to add a transition to my ember modal.

I'd like fade in - like this - http://ift.tt/1QnTARE (see bottom of the page).

My code: app/templates/components/hello-modal.hbs:

<div> !</div>
<div></div>
<button  class="done">Thanks</button>
<button  class="change">Change</button>

app/components/hello-modal.js:

export default Ember.Component.extend({
  classNames: ['hello-modal'],
  actions: {
    gotIt: function() {
      this.sendAction('dismiss');
    },
    change: function() {
      this.sendAction('changeSalutation');
    }
  }
});

step 3 ( as you can see from the example in link says): 'Call modal() within your router map, at whichever scope you choose and wire up any actions:'

Not sure I understand this. But I added it to my cupcakes router:

router.js

Router.map(function() {

            this.route('device');
            this.route('cupcakes', function() {
              this.modal('hello-modal', {
                withParams: ['salutation', 'person'],
                otherParams: {
                  modalMessage: "message"
                },
                actions: {
                  changeSalutation: "changeSalutation"
                }
              });        

    });

cupcakes.hbs


    Try It


controllers/cupcakes.js:

export default Ember.Controller.extend({
  queryParams: ['salutation', 'person'],
  salutation: null,
  person: null,
  modalMessage: "bound text for modal",
});

Nothing happens when I click 'try it' on cupcakes.hbs And no error messages show in the console.




d3 Events not triggering

I'm using D3's arc shape and have attached the D3 drag handler to catch drag movement. Looking at the browser's debugger:

enter image description here

You can see that the resulting Arc's path is indeed listening for the appropriate events and yet the callbacks are never fired and no JS errors are reported to the console.

The code used to add the handlers (as well as the callbacks) are here. For those of you familiar with Ember, great, for those of you not I've tried to only show the relevant JS parts.

import { drag } from 'd3-drag';
import { arc } from 'd3-shape';
import { select } from 'd3-selection';

const uiArc = Ember.Component.extend({
  layout,
  tagName: '',
  init() {
    this._super(...arguments);
    Ember.run.schedule('afterRender', () => {
      this.svg = document.getElementById(this.elementId);
      this.addDragListeners(`#${this.elementId} .unselected`);
    });
  },

  addDragListeners(target) {
    drag.container = this;
    select(target).call(drag().on('start', this._dragStart));
    select(target).call(drag().on('drag', this._dragging));
    select(target).call(drag().on('end', this._dragEnd));
  },

  _dragStart(e) {
    console.log('drag starting', e);
  },
  _dragging(e) {
    console.log('dragging', e);
  },
  _dragEnd(e) {
    console.log('drag ending', e);
  },

Can anyone help me figure out how to debug this or suggest what might be wrong?

Note: I am using d3 version 4, latest build as of today (30 May, 2016)


For additional context, here too is the Handlebars template responsible for drawing the path:

<path
  d=
  class='unselected'
  style="stroke: ; fill: ;"
></path>

Nothing very remarkable here, it's just to point out that the template does not invoke any native DOM events and that the class name of "unselected" is available in the DOM for the d3 selector to find it (which it appears to have done; hence the DOM event listeners showing up in debugger).




EmberJS - Server side generated variable

We are building our front-end application in EmberJS. We do several calls to a service (via Ajax) that requires a token.

This token is created by another request to this service.

All the clients will use the same token, so, ideally, it would be great to generate this token in the server side and provide this value in a global variable to all the clients.

Is it possible to do it in EmberJS, for example, when the nodeJS starts the application?




bind values to application.hbs from different routes

In Ember.js (version 2.5.1), I have the following code in my application.hbs:

<div class="content-wrapper">
    <section class="content-header">
        <h1>
            <small></small>
        </h1>
    </section>
    <section class="content">
        
    </section>
</div>

Where should I declare and properties so they can change depending on the current route? I thought of generating an application controller (ember g controller application) which works fine for the index route, however, I am unable to change these properties if I navigate to other routes in my application.




Compile Ember CLI project assets to multiple JS files

I've got a project with a need for multiple JS files. Some use cases:

  • IE-only polyfills I include with a conditional comment and don't want mobile devices to download
  • Large files not included on a landing page that I want to lazy load

It appears that ember cli allows for multiple CSS files, but not multiple JS files:

venter code herear app = new EmberApp({
  outputPaths: {
    app: {
      js: {
        app: '/assets/app.js',
        ie: '/assets/ie.js'
      }
    }
  }
});

Errors:

Object #<Object> has no method 'slice'
TypeError: Object #<Object> has no method 'slice'
    at module.exports (/Users/<me>/Projects/<my-app>/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/index.js:15:30)
    at EmberApp.concatFiles (/Users/<me>/Projects/<my-app>/node_modules/ember-cli/lib/broccoli/ember-app.js:261:10)
    at EmberApp.javascript (/Users/<me>/Projects/<my-app>/node_modules/ember-cli/lib/broccoli/ember-app.js:864:16)
    at EmberApp.toArray (/Users/<me>/Projects/<my-app>/node_modules/ember-cli/lib/broccoli/ember-app.js:1159:10)
    at EmberApp.toTree (/Users/<me>/Projects/<my-app>/node_modules/ember-cli/lib/broccoli/ember-app.js:1181:30)
    at Object.<anonymous> (/Users/<me>/Projects/<my-app>/Brocfile.js:35:22)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

There's nothing in the guides about multiple JS files other than vendor; is there something I'm missing or is this a missing feature?




Not getting response from socket.io configured with nginx

Created a node.js app and configured with nginx reverse proxy. The app was working fine till i configured it with nginx. But then in nginx application is able to connected to server but the connection is not reverted back client. But server is printing logs as it is connected. The code snippets are below. And I forget to mention i use socket-io with ember.js

nodejs/server.js

var express = require('express')
  , app = express()
  , http = require('http')
  , server = http.createServer(app)  
  , io = require('socket.io').listen(server);

server.listen(3000);


io.sockets.on('connect', function (socket) {
  console.log('------------->> Client Conected !!'); 


  socket.on('message', function (msg) {   
        onMessage(msg); 
   });

  function onMessage(msg) {      
      console.log('------------->> client msg - '+msg);       
   }

  socket.on('disconnect', function () {      
      console.log("------------->> Client disconected !!");
    });  
 });
console.log("server started @ 3000");

emberjs/socketio-client-controller.js

import Ember from 'ember';

export default Ember.Controller.extend({
  socketIOService: Ember.inject.service('socket-io'),
  init: function() {
    this._super.apply(this, arguments);
    var socket = this.get('socketIOService').socketFor('http://ift.tt/1TRflhS');
  socket.on('connect', function() {
      console.log("connected");
      socket.send('Hi Server');
      socket.on('message', this.onMessage, this);
    }, this);
  },

  onMessage: function(data) {
      console.log(data);
  }
});

This was working fine till nginx came to play. But still managed to configure as below

nginx.conf

http {

    upstream node {
        server ip-node-app:3000;
    }   

 server {
        listen       80;
        server_name  nginx.domain.com;

            location / {
            root   html;
            index  index.html index.htm;
        }

           location /socketio/server {
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header Host $http_host;
             proxy_set_header X-NginX-Proxy true;           
             proxy_buffers 8 32k;
             proxy_buffer_size 64k;
             proxy_pass http://node;
             proxy_redirect off;          
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";      
        }

        location /socket.io {
           proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header Host $http_host;
             proxy_set_header X-NginX-Proxy true;           
             proxy_buffers 8 32k;
             proxy_buffer_size 64k;
             proxy_pass http://node;
             proxy_redirect off;          
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";      
        }       
        }
    }

Once the client triggers request to server I'm seeing the console.log printing

"------------->> Client Conected !!"

but the client doesn't get any response from server at all(which means the client won't connect to server but server receives client connection's request). What Am I missing here?




How does Ember map function expect parameters?

I want to understand how the below code works in EmberJS?

Ember.$.map($this.get('myMap'), function(entitlements, id) {
    // What is entitlements & id here & what should be $this.get('myMap')?
})

is this conventional/standard JS syntax ? Any examples would be great ?




Ember addon tests hang on "Waiting for runners" for Chrome and Firefox

Even I've mentioned Chrome in testem.json as the following, nothing happens:

"launch_in_dev": [
  "PhantomJS",
  "Chrome"
]

If only "Chrome" is written, console displays "Waiting for runners..." messsage and hangs.

package.json, bower.json and testem.json are all the same with my other projects, and all others are all running on Chrome.




How to resize a "div" based on mouse drag in EmberJs?

I am building grid in which the header needs to be resizable.

Basically, User can click on the edges of the header column then drag it for resize.

Currently I have a component for each header column and I suppose it needs some event handling here but I cannot figure out which one.

Please suggest on what approach should be followed.

Note: I am using Ember version 1.13. Also, cannot use ember-table.




Emberjs: How to invalidate session in custom authentication initializer

I'm using ember-simple-auth 1.1.0 with cookie authentication and I created a custom authenticator with functions (restore, authenticate and invalidate) and an initializer of the custom authenticator.

I bind on ajaxError event so we can catch any errors. For example accessing a route with a server response 401 Not Authorized. I would like to invalidate the session and redirect the user back to the login page.

At the moment I'm not able to get the ember-simple-auth default session in the initializer so I can invalidate the session. I didn't create any custom session for my application.

What is the best way to do this?

If it is not possible, is it better to trigger an event on initializer and catch that event in a route? How we can do this?

My custom initializer looks like:

import BasicAuthenticator from '../authenticators/basic';

export default {
  before: 'ember-simple-auth',
  name: 'basic-authenticator',
  initialize(application) {
    application.register('authenticator:basic', BasicAuthenticator);
    Ember.$(document).ajaxError((event, jqxhr, settings, reason) => {
      if (jqxhr.status === 401) {

      }
    });
  }
};

My Custom Authenticator:

import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';

export default Base.extend({
  restore() {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      let sessionCookie = window.Cookies.get('beaker.session.id');
      if(!window.isUndefined(sessionCookie)) {
        resolve(true);
      }else{
        reject();
      }
    });
  },
  authenticate(data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/login',
        data: data
    }).then((response) => {
        resolve({
          responseText: response
        });
      }, (error) => {
        reject(error);
      });
    });
  },
  invalidate() {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/logout'
      }).then(() => {
         resolve(true);
       }, () => {
         reject();
      });
    });
  }
});




dimanche 29 mai 2016

(Drag n drop) Dragula.js not working on revisiting the route (in ember.js app)

I am using dragula.js library in an ember.js web app.

Things are working fine (able to drag and drop things) until I revisit the route, after which drag and drop just stops working, that is, can't drag anything that was previously draggable. And there are no js errors in console. Then, I refresh the page (from any route), it works again.

In short, the drag n drop works only for the first time when the route is visited/loaded.

Things I tried:

  • Verified if the DOM items to be drag n dropped, are added to dragula's config.containers.
  • Tried Rerendering the component from didInsertElement element inside the run loop running in afterRender.

didInsertElement(){ this._super(...arguments); Ember.run.scheduleOnce('afterRender', this, () => { let drake = window.dragula(this.getDraggableContainers(), this.get('dragulaConfig')); this.set("drake", drake); }

To me, it seems like the dragula library is initialized with all the required config, but I am baffled why its NOT working correctly after revisiting the route.

Any help/pointers would be greatly appreciated. Thanks!




Ember.js: Pass options to node.js

I'm trying to build some LESS code (via ember-cli-less) to CSS file.

1) http://ift.tt/1F4prXX AdminLTE LESS files 2) Bootstrap LESS files.

And I got:

⠸ Building
<--- Last few GCs --->
87632 ms: Scavenge 1403.1 (1458.1) -> 1403.1 (1458.1) MB, 92.0 / 0 ms (+ 19.3 ms in 1 steps since last GC) [allocation failure] [incremental marking delaying mark-sweep].
90306 ms: Mark-sweep 1403.1 (1458.1) -> 1399.0 (1457.1) MB, 2674.4 / 0 ms (+ 1196.1 ms in 2698 steps since start of marking, biggest step 21.2 ms) [last resort gc].
93043 ms: Mark-sweep 1399.0 (1457.1) -> 1396.1 (1458.1) MB, 2737.2 / 0 ms [last resort gc].


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x26d2e65b4629 <JS Object>
1: eval [/home/ofry/my-new-lk/node_modules/less/lib/less/tree/ruleset.js:~33] [pc=0x2f428a9933db] (this=0x26d2e6581591 <JS Object>,context=0x289d4931c589 <JS Object>)
2: eval [/home/ofry/my-new-lk/node_modules/less/lib/less/tree/ruleset.js:~33] [pc=0x2f428a992d84] (this=0x289d4931c7a1 <JS Object>,context=0x289d4931c589 <JS Object>)
3: evalCall [/home/ofry/my-new-lk/node_modules/less...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

So I need to pass somehow --max_old_space_size=big_number when launch

ember build

How I can do this?




EmberJS - the run loop is cleared with "asyn/await" instead of the use of "then"

I have a strange behavior with run loop in a test (yes, for everybody is difficult ;-) ) and with the babel plugin async to generator transform.

First, I have "an old school code":

await Ember.run(function() {
  return task.save().then(() => {
    subtask_1 = task.create_subtask();
    return subtask_1.save();
  }).then(() => {
    subtask_2 = task.create_subtask();
    return subtask_2.save();
  }).then(() => {
    subtask_3 = task.create_subtask();
    return subtask_3.save();
  }).then(() => {
    subtask_4 = task.create_subtask();
    return subtask_4.save();
  }).then(() => {
    return subtask_4.promise_priorize_before(subtask_2);
  });
});

It works. ;-)

But, if I tried, I think the equivalent code with the "new way", I have an error:

await Ember.run(async function() {
  console.log(Ember.run.currentRunLoop);
  await task.save();
  console.log(Ember.run.currentRunLoop);

  subtask_1 = task.create_subtask();
  console.log(Ember.run.currentRunLoop);
  await subtask_1.save();
  console.log(Ember.run.currentRunLoop); // <---- null here

  subtask_2 = task.create_subtask();     // <---- crash here
  console.log(Ember.run.currentRunLoop);
  await subtask_2.save();

  subtask_3 = task.create_subtask();
  await subtask_3.save();

  subtask_4 = task.create_subtask();
  await subtask_4.save();

  return subtask_4.promise_priorize_before(subtask_2);
});

I don't understand why, but the current run loop is cleared after a simple "save" of Ember data.

The error is "Assertion Failed: You have turned on testing mode,… any code with asynchronous side-effects in a run" because Ember.run.currentRunLoop is null.

Have you an idea?

Frédéric




samedi 28 mai 2016

Is there any way I can enforce an "API contract" when testing my web app's API and UI separately?

I'm developing an Ember.js app with a Phoenix API. I have followed someone's advice to keep the UI and API as separate projects, and I know that I can use ember-cli-mirage to mock my API during development and testing. But this makes me really nervous. I'm used to having a suite of integration tests that tests the UI and API together. I know for a fact that one day me or another developer is going to make a breaking change in one of the projects, and we won't realise it until users start complaining.

On the other hand, I really like the idea of mocking the API in the client where Ember.js is running. It should make development and testing really fast.

Is there a way that I can extract a high-level description of my API end points, and use that as a sanity check to make sure that my mocked API fulfills all of the requirements? For example, if I add or remove a route in my API server, I want my Ember.js tests to fail immediately if the mocked API doesn't match those changes. Because I know that this is going to happen one day. It's especially concerning if I want to use continuous deployment after successful builds.

Or should I just start up a real API server on the CI machine, and run my tests against that?

I kind of like the idea of enforcing an API contract, though. I could also reuse the principle in any future mobile or desktop apps. You get some guarantee of consistency without having to install a ton of dependencies and spin up a real API.

Another idea: Maybe I write a set of API acceptance tests, but run them against both the real and the mocked API. And then I could include the mocked API code (ember-cli-mirage) inside my main API repo, and link it into the Ember.js repo as a submodule.

How are people currently approaching this issue?




Looping through an Ember JS RSVP hash?

Code speaks a thousand words; is there a way to do what I'm attempting here?

Users "Root" Route

Loading common selectable options at the top level for use within sub-routes such as index, show, edit, create, etc...

-- /pods/users/route.js

model() {
    return RSVP.hash({
        userCategories: this.store.findAll('user-category'),
        userSources:    this.store.findAll('user-source'),
        userGroups:     this.store.findAll('user-group'),
    });
},

Users "Create" Route

With the sub-route of /create I want to loop through the already-loaded options above and load them into the template as named variables:

-- /pods/users/create/route.js

setupController(controller, model) {

    let rootModel = this.modelFor('users');

    rootModel.forEach(function (model, name) {
        set(controller, name, model);
    }); <-- THIS IS THE BROKEN PART...

    ...

}

The Problem

On the .forEach loop I am getting Error while processing route: rootModel.forEach is not a function TypeError: rootModel.forEach is not a function

Is there an "Ember Way" of looping through that root model, or will I be stuck with loading it in within a top level variable, ie;

-- /pods/users/create/route.js

setupController(controller, model) {

    let rootModel = this.modelFor('users');

    set(controller, 'rootModel', rootModel);

    ...

}




How do I depend on all properties of an Ember Object?

I want to create a property which represents an Object stringified. It should update whenever any sub property of the object changes even if it isnt a direct child.

I.e.

var obj = Ember.Object.extend({jsonString: Ember.something()}).create({foo: 1, bar: 2, baz: Ember.Object.create({bam: Ember.A([1, 2, 3])})});
expect(obj.get('jsonString')).to.equal('{"foo": 1, "bar": 2, "baz": {"bam": [1, 2, 3]}}');
obj.set('foo', 3);
expect(obj.get('jsonString')).to.equal('{"foo": 3, "bar": 2, "baz": {"bam": [1, 2, 3]}}');
obj.set('foo.baz.dd', 'test');
expect(obj.get('jsonString')).to.equal('{"foo": 3, "bar": 2, "baz": {"dd": "test", "bam": [1, 2, 3]}}');

Thanks!




How to view all response headers in ember with RESTAdapte

My response headers look like this

HTTP/1.1 200 OK
Server: nginx/1.9.7
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
X-On-Trial: 1
Cache-Control: no-cache
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Date: Sun, 29 May 2016 00:37:31 GMT

But when I do a console.log(headers) in the RESTAdapter handleResponse function, all that is included is

EmptyObject {Content-Type: "application/json", Cache-Control: "no-cache"}

How can I access the X-On-Trail header or any other custom headers I may need?

I'm not sure if this matters but I am using ember-simple-auth. Does that strip out headers?




In Ember, how to include radio button and how to get changed value ember-radio-button component

I used http://ift.tt/25plgA1 to include radio button,



I don't know how to get the changed value in colorChanged method in My component.

export default Ember.Component.extend({
actions: {
 colorChanged(){
  console.log('Color changed ');
 }
} });




How to highlight code in hbs template?

I want to introduce into my project some code to be highlighted on certain pages (like index.hbs) I've searched for libraries that can do this and found tools like highlight.js, but I was unable to use it in my ember project. Can anyone explain how to import a custom library like highlight.js or can someone give me a recomandation for a tool. I've tried to use this tool: ember-cli-eg-code-highlight, but it is not specified how to use it. Ok I have installed it, pasted the in my index.hbs, but it does not work. Also the ENV.emberHighlightJs: { style: 'arta' };I have no ideea where to put it. Tried to put it inember-cli-build.js but it is not working.

I have found also markdown-code-highlighting. But I am lost at this step: "In your Brocfile you'll need to import the CSS styling you want for the highlighter. " So where exactly is my brocfile in my ember project?




vendredi 27 mai 2016

How do I access the variable of a dynamic route in EmberJS

I've done

ember g route auth
ember g route auth/pending

Which then gave me :

app/
  routes/
    auth/
      pending.js
    auth.js

and my router has

  this.route('auth', function() {
    this.route('pending', { path: '/pending/:steamid/:token'});
  });

Which everything is fine, when I visit

http://localhost:4200/auth/pending/1/2

The page loads, but how do I access :steamid and :token outside of the model.

I'd like to use it so that I can set values in my session service

Like:

import Ember from 'ember';

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

  steamID: this.get(// Params Some How),
  token: this.get(// Params some How)

  thing(params) {
    this.get('session').set('tokenID', token),
    this.get('session').set('steamID', steamID)
  }
});

^^ Pseudo code to express what I'm trying to accomplish.




How do I supply an index route with a template Ember 2?

I want to create an ember application as follows:

var app = Ember.Application.create({
  rootElement: document.getElementById('root'),
  name: 'my-application',
  IndexRoute: Ember.Route.extend({
      model: function() {
        console.log('model');
      },
      afterModel: function(model, transition) {

      },
      template: Ember.Handlebars.compile('<div id="test"></div>'),
    }),
  locationType: 'hash',

});

The problem is that I dont get the test div in the DOM. How come?

http://ift.tt/1TJFi6f




Authentication failed - Permission Denied with EmberFire

I'm trying to set up a basic datastore at firebase when following simple beginner tutorials on Ember js 2.0. For example I am following this tutorial:

http://ift.tt/1UjviNU

I always seem to have a problem with authentication with the Firebase URL. That is, I've gotten to the bit where this tutorial tries to write information to my firebase project, but the Chrome Inspector shows I'm getting a 'permission denied' error from firebase.

FIREBASE WARNING: update at /posts/-KIpiNcp3WVRkCfwl_lW failed: permission_denied

I have installed emberfire with ember install emberfire. I have added my firebase URL to config/environment.js:

contentSecurityPolicy: { 'connect-src': "'self' HTTPREMOVED//auth.firebase.com http://ift.tt/1Us4oBa" }, firebase: 'HTTPREMOVED//ember2-blog-ccb21.firebaseio.com',

Note: I had to remove the http element on these links to post here as I have a reputation less than 10.

Initially I did not change any authentication settings on my Firebase project (which I think is odd as I should need to authenticate to the Firebase project somehow). Then I tried adding my domains, firstly my IP and then the domain name associated with my IP.

I'm using: ember-cli: 2.5.1

I'd love it someone could point me in the right direction. Thank you.




How do I supply the index route with a template Ember 2?

I want to create an ember application as follows:

var app = Ember.Application.create({
  rootElement: document.getElementById('root'),
  name: 'my-application',
  IndexRoute: Ember.Route.extend({
      model: function() {
        console.log('model');
      },
      afterModel: function(model, transition) {

      },
      template: Ember.Handlebars.compile('<div id="test"></div>'),
    }),
  locationType: 'hash',

});

The problem is that I dont get the test div in the DOM. How come?

This yields the same problem:

var app = Ember.Application.create({
  rootElement: document.getElementById('root'),
  name: 'riotclient-launcher',
  IndexRoute: Ember.Route.extend({
      model: function() {
        console.log('model');
      },
      afterModel: function(model, transition) {

      },
    }),
  TEMPLATES: {
    index: Ember.Handlebars.compile('<div id="test"></div>'),
  },
  locationType: 'hash',

});

http://ift.tt/1TJFi6f




include bower component in Ember Controller

I am trying to use js-beautify in my ember application. The module is imported in app.import('bower_components/js-beautify/js/lib/beautify.js'); in ember-cli-build.js but i dont know how to use the beautify.js. how can i import the package in my controller? I tried something like this: import Ember from 'ember'; but with my bower_components/js-beautify/js/lib/beautify.js route but it refused to work.




Ember.js/Ember Data takes several minutes to update hasMany of parent after creating thousands of child records

I'm new to Ember.js and running into performance issues when trying to create thousands of records (5300 to be exact) and updating a hasMany relationship. I'm making a request to my API to retrieve records before I create my new records. After the promise returns, I then do a forEach over each record brought down (5300) to do my calculations for the new set of records. Creating the records themselves takes about 2 seconds. Updating the hasMany starts off quickly only for the first 40 or so records and then slows to about one update per second.

I should also note that this is being done within a component. I know this is typically anit-pattern, but in this case there is no reason to change the URL or transition. This is a screen where users can select from a pool of items (provided by the route), apply a pricing rule, and then create an event (created in the route) based on those items. It's a sandbox to determine what items will be a part of the event. Once the users have decided on their items for the event, I then send an action up to the route to perform the actual save and persist to my backend. Outside of the anti-pattern aspect, I can't see how this would affect the performance of the hasMany update.

I'm using RESTAdapter and RESTSerializer for what it's worth, but that should not have any impact here since I'm just dealing with the Ember data store.

Ember Version:

Ember             : 2.5.1
Ember Data        : 2.5.3
jQuery            : 2.2.3
Ember Simple Auth : 1.1.0

The two models in question are as follows...

Child Model (event-item):

export default DS.Model.extend({
  event: DS.belongsTo('event'),
  itemNumber: DS.attr('string'),
  styleNumber: DS.attr('string'),
  tier: DS.attr('string'),
  eventPrice: DS.attr('number')
});

Parent Model (event):

export default DS.Model.extend({
  eventTypeId: DS.attr('string'),
  eventName: DS.attr('string'),
  eventDesc: DS.attr('string'),
  startDate: DS.attr('moment-date'),
  endDate: DS.attr('moment-date'),
  priority: DS.attr('number'),
  statusCode: DS.attr('string'),
  value: DS.attr('number'),
  eventItems: DS.hasMany('event-item', {async:true})
});

Event create record:

model() {
    return this.store.createRecord('event', {});
},

Code block in component responsible for creating records and updating hasMany:

this.get('store').query('pricing', {brandCd: '00'}).then(tiers => {
    tiers.forEach(tier => {
        this.get('event').get('eventItems').createRecord({
            styleNumber: tier.get('styleNumber'),
            itemNumber: tier.get('itemNumber'),
            brandCd: '00',
            tier: tier.get('tier'),
            eventPrice: this._calculateEventPrice(tier.get('origPrice'), this.get('event').get('eventTypeId'), this.get('event').get('value')),
        });
    });

    this.get('event').set('needsUpdated', 'Y');
});

So far I've tried the following...

  • Adding inverse relationships to my hasMany and belongsTo
  • Adding all of the create records to an Ember.A() and then trying to push the new records to the hasMany like so: this.get('event').get('eventItems').pushObjects(newEventItems);. Also tried it using this.get('event').get('eventItems').addObjects(newEventItems);.
  • Setting the belongsTo on the record being created instead of updating the hasMany of the parent (event).
  • I also went ahead and moved this logic into my route just to make sure I wasn't getting odd behavior by doing this in the component. It performs the same.

I would assume (and please correct me if I'm wrong) that creating records and updating relationships strictly on the client side should be able to handle thousands of records without too much issue. I'm hoping I'm just doing something incorrect or in an inefficient way that will be obvious to someone with more experience. Any help, including alternatives, is greatly appreciated!




Trouble with Ember project - filling a text-field based on selection

I've never worked with Ember, and am fairly new to JavaScript, and have for the past couple of days been trying to translate my HTML and JS into the Ember framework (I got some help from a friend). The first feature of the project should simply be able to fill a text-field with longitude/latitude of an inputted address. The second feature of my project is based on a selection from a drop-down menu (drop-down is made of different counties), and fill another text-field with a specific email address depending on which selection was made.

The problem I'm having: I can't seem to figure out how to fire up my setEmail function as I need it to recognize a value (1, 2, 3, 4 etc.) from the selected county from the drop-down, and based on that value; fill in the text-field with the correct email address. I've heard about Ember Observers, but cannot seem to figure out how to implement them for the drop-down I built. I'd really appreciate if someone could take a look at my project and give me pointers on what I could improve, or even do completely differently.

Here is a link to an Ember Twiddle of my project: GeoApp

I appreciate any suggestions and insight! Thank you.




Ember model unnamed JSON variable

I'm trying to consume the following JSON response in Ember.

[
  {
    "url": "https://example.com",
    "files": {
      "config.json": {
        "name": "config.json"
      },
      "style.css": {
        "name": "style.css"
      }
    },
    "user": null
  },
  {
    "url": "https://newexample.com",
    "files": {
      "settings.json": {
        "name": "settings.json"
      },
      "index.html": {
        "name": "index.html"
      }
    },
    "user": null
  }
]

Here's my first model "snippet":

export default Model.extend({
  url: attr('string'),
  files: hasMany('file')
});

And then my "file" model with which I created a hasMany Relationship to:

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

index.js route:

export default Ember.Route.extend({
  model() {
    return this.store.findAll('snippet');
  }
});

I realise that this won't work since I'm not defining the first variable in "files". Though I can't figure out how one would do this since this variable is dependent on the filename.

Any help would be appreciated. Thanks.




EmberJS, WordPress REST API and categories and tags

I’ve started playing with ember and trying to combine the WordPress REST API and EmberJS. I‘m stucking with this problem: I want ember to show me all WordPress posts from a certain category or tag.

I have a route that shows me all categories routes/categories.js that are in the category model models/category.js. Now I need a route for each category routes/categories/category.js, that shows me all posts within a certain category.

post and category are two models, that I need to get combined I guess, but I do not know how ...

In routes/categories.js I have something like this

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      categories: this.store.findAll('category'),
      posts: this.store.findAll('post')
    });
  },
  setupController(controller, model) {
    this._super(...arguments);
    Ember.set(controller, 'categories', model.categories);
    Ember.set(controller, 'posts', model.posts);
  }
});

And in templates/categories.hbs this

<p>List of all categories in the model</p>
<ul>
    
        <li></li>
    
</ul>

Now I want to see all posts that are in this category routes/categories/category.js

export default Ember.Route.extend({
    model(params) {

        ...???...

    }
});

and in templates/categories/category.hbs ?

<h3>List all posts from the selected category</h3>
<ul>
    
        <li></li>
    
</ul>

Someone able to help with this?




ember modal dialog wont close

I have used ember-modal-dialog. I have set the modal to close (as per the example on git - http://ift.tt/1JBG5dZ). But it does not close when I click the background.

application.hbs


  
      abc
  


applications.js

export default Ember.Controller.extend({
    isShowingModal: false,
    actions: {
        showNavMenu: function() {
          this.toggleProperty('isShowingModal');
        }
    }
});




Ember app and google crawler

I'm trying to make my ember application crawlable. As I know Google supports JS, CSS and AJAX now (from october 2015). But when I test my site by "Fetch as Google" I get empty page with background: http://ift.tt/1U0BOGF

In real of course I have content and page looks completely different: http://ift.tt/1TN9tHS

What I'm doing wrong?




if withdraw set value to #value1 else #value2

({
  selectDefaulAmt: (function() {
    if ('currentPath' === '??') {
      return this.send('selectAmount', 50);
    } else {
      return this.send('selectAmount', 100);
    }
  }).on('didInsertElement')
});

I need to change value based on current url, some advice ??




AJAX promise call handling

I have an Ember promise call as below;

var promise = new Ember.RSVP.Promise(function(resolve, reject) {
    return $.ajax({
    //want this common
        url: requestUrl,
        type: type, // HTTP method
        dataType: dataType, // type of data expected from the API response
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(postData)
    })
    .done(function(data, status, xhrObject) {
    //But want this to be different
      // resolve call
    })
    .fail(function(xhrObject, status, error){
      // reject call
    });
})

My question is can I use common code for $.ajax(), but have different implementation for done() callback I can check that by passing some parameter from the calling place.

so basically, I want

if (someparam == 'handleDone1')
    call resolve(data)
else
    call resolve({data})




ember-cp-validations: Validation on htmlbar does not work

- My problem is that the validation on the htmlbar new.hbs does not work. It is so confused for me, because I have a basic Ember project. I went through the tutorial on github step by step and it just does not work.

What I've done is that:

  • add Validations variable to rental.js model
  • add helper v-get to new.hbs

I should be grateful if you could help me figure out why it does not work.

This is my project on github. Version of Ember that I used is 2.5.0.




ember if else conditionals

I have a conditional statement which contains a link. If something is true, the I'd like it to link to a 'place a' if it is not true I'd like it to link to 'place b'. But I am getting a build error.

I removed the conditional statement, and just have a normal link (link-to) ...so just a link to one place my code builds fine. The build error is just when I try to have 2 links. See below:

        <div class="card text-xs-center">
          
          
          
            
          
              <div class="card-block">
                  <i class="fa fa-cogs" aria-hidden="true"></i>
              </div>
              <div class="card-block">
                  <h4 class="card-title">The Place</h4>
              </div>
          

        </div>

The error says: Error: link-to doesn't match if - 8:19




404 page not found when a url is hit but properly served when opened from the link on index page

I am using nginx-lua module with redis to serve static files of ember-app. The index file content is stored in redis as a value which is being properly served by nginx when the (root) domain/IP is hit.

If login page is open from link, it gets opened properly. But when opened directly by hitting the url bar or refreshing the page the nginx gives 404 not found. The index file is in redis and rest of the files are being served from compiled js which is present on a CDN. Following is the nginx configuration

server
{
  listen 80 ;
  server_name 52.74.57.154;

  root /;

 default_type   text/html;
 location = / {
    try_files $uri $uri/ /index.html?/$request_uri;
    set_unescape_uri $key $arg_index_key;
    set $fullkey 'ember-deploy-cli:index:${key}';

     content_by_lua '
                local redis = require "resty.redis"
                local red = redis:new()

                red:set_timeout(1000) -- 1 sec



                local ok, err = red:connect("127.0.0.1", 6379)
                if not ok then
                    ngx.say("failed to connect: ", err)
                    return
                end


        if ngx.var.key == "" then
            --ngx.say("No Argument passed")
            local res, err = red:get("ember-deploy-cli:index:current-content")
            ngx.say(res)
            return
        end
        local res, err = red:get(ngx.var.fullkey)

        if res == ngx.null then
            ngx.say("Key doesnt exist ")
            return
        end
        ngx.say(res)

     ';
 }




EmberJS putting multiple data on a route

I want my detail page to include 2 little links(with image) like "next 2 news". How can I do it? my twiddle: http://ift.tt/20GAz42

In my detail page which is "pic" route, I print the selected image's bigger version and its content. How am I gonna add two more little pics,to the bottom of the page for example, which are next 2 news' links? If I use "model.blah" it only takes the one I selected. Is there any other way?




best book to learn ember.js

I wants to get learn ember.js. so tell me the best book to learn ember.js.




How can I use OpenID with my own RESTful API?

I'm currently creating an EmberJS application,

So obviously my front end is done in EmberJS, and I've decided to go with Go (Golang) as my API service.

I've gotten the back end authentication working using Steams OpenID service

The problem I'm currently facing is, my API runs on localhost:3000 and my front end runs on localhost:4200.

So how can I make a request to my API service which will require human intervention part way through (to be able to type in the username / password on steams website before redirecting back) from my client side.

Right now

localhost:3000/auth/login is to initiate the OpenID request which redirects to steams website

and then

localhost:3000/auth/return is the callback on returning from steams website

I need to be able to some how use this authentication from the client side via some how to be able to authenticate users, e.g.:

$.get("localhost:3000/auth/login").then(() => { 
    // How the hell am I supposed to login on steams website from here
});

any information would be great as this is really stumping me. If you'd like to see any code feel free to ask, I'm not sure what to provide as everything is working as intended, but I just can't figure out how to connect the API to the client and make OpenID work the way I need to. Thanks!

Side Note: I know some websites will have a popup which the authentication in there (like a twitter or facebook popup) and then refresh the main site after the authentication has been processed I don't know how I might achieve something like that.




Ember Cli Deploy via Lighting Strategy

We have deployed our Ember App using Lightning Deploy Strategy which involves:

  • EC2 instance
  • Nginx (HTTP Server)
  • Redis, configured on same instance (to serve index.html)
  • compiled js and assets from AWS S3

When, upon hitting the instance, the index.html gets served from Redis, and subsequently on clicking any route in the App, the App routes get served.

But, when we manually enter any correct route in URL for the Ember App, Nginx throws an error saying route not found. Anything wrong that we are doing here?




jeudi 26 mai 2016

ember-data with customization for use with non-JSONAPI service

I am a bit confused and just need some clarity: Should I be implementing a custom adapter or a custom serializer?

I need my ember app to talk to a REST/json backend.

I want my ember app to expose the resource as:

GET /locations/:id

But the host it connects to has the resource located at:

GET http://server/api/location/:id

Payload from the server:

{
  "id": "7ff3269e-d16c-4cc4-954d-aef8e662e0f6",
  "geo": {
    "latitude": 0,
    "longitude": 0
  },
  "typedAddress": {
    "addressType": "US",
    "countryCode": "US",
    "name": "string",
    "address1": "string",
    "address2": "string",
    "address3": "string",
    "postalCode": "string"
  },
  "customDescription": "string",
  "timezone": "string"
}

My model in ember for this:

export default Model.extend({
  latitude: attr('number'),
  longitude: attr('number'),
  addressType: attr('string'),
  countryCode: attr('string'),
  address1: attr('string'),
  address2: attr('string'),
  address2: attr('string'),
  city: attr('string'),
  state: attr('string'),
  briefPostalCode: attr('string'),
  postalCode: attr('string'),
  timezone: attr('string')
});




Ember-Data: embedded objects in JSON data is lost

I have a model called ticket-stats, defined as follows:

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

export default Model.extend({

    opened24Hours: attr('number'),
    miRelated: attr('number'),
    autoClosed24Hours: attr('number'),
    inQueue: attr('number'),
    activeGreater48: attr('number'),
    behindNct: attr('number'),
    manuallyClosed24Hours: attr('number'),
    handoff: attr('number')

});

The data for this comes from a service which yields the following JSON:

{
  "get_tickets": {
     "behind_nct": {
        "inequality": null,
        "stat_name": "Behind NCT",
        "value": 0,
        "update_time": "2016-05-26 18:05:11",
        "threshold": null
      },
      ...
   }
}

I have a custom serializer for this model:

import JSONSerializer from 'ember-data/serializers/json';

export default JSONSerializer.extend({

    normalizeResponse(store, primaryModelClass, payload, id, requestType) {
        console.log(payload);
        var data = {};
        data.id = 1;
        data.opened24Hours = payload.get_tickets.tickets_opened_last_24_hours.value;
        data.miRelated = payload.get_tickets.mi_related_tickets.value;
        data.autoClosed24Hours = payload.get_tickets.tickets_closed_goliath_last_24_hour.value;
        data.inQueue = payload.get_tickets.tickets_in_queue.value;
        data.activeGreater48 = payload.get_tickets.active_greater_48.value;
        data.behindNct = payload.get_tickets.behind_nct.value;
        data.manuallyClosed24Hours = payload.get_tickets.tickets_closed_last_24_hours.value;
        data.handoff = payload.get_tickets.handoff_tickets.value;

        return this._super(store, primaryModelClass, data, id, requestType);
    }

});

The values for the attributes of my model are all null. When i look at the payload on the console, I see that the innermost objects (i.e. behind_nct) don't contain the correct attributes:

behind_nct: Object
  __proto__: Object
  __defineGetter__    :    __defineGetter__()
  __defineSetter__    :    __defineSetter__()
  __lookupGetter__    :    __lookupGetter__()
  __lookupSetter__    :    __lookupSetter__()
  constructor    :    Object()
  hasOwnProperty    :    hasOwnProperty()
  isPrototypeOf    :    isPrototypeOf()
  propertyIsEnumerable    :    propertyIsEnumerable()
  toLocaleString    :    toLocaleString()
  toString    :    toString()
  valueOf    :    valueOf()
  get __proto__    :    get __proto__()
  set __proto__    :    set __proto__()

Is there something wrong with the JSON api or with my configuration of the Ember model? Or both?

When i go to the URL for the json, everything seems fine. I can see all the data.




Heroku push fails: Error: `libsass` bindings not found. Try reinstalling `node-sass`?

I'm trying to push a new app to Heroku but I'm getting this libsass error:

Error: ´libsass´ bindings not found. Try reinstalling ´node-sass´?

I've looked all around but the solutions I've found are for a local environment, but I have no problem on my machine.

One of the things I found was to use node 0.12.0, I was on 0.10, but Heroku is already on 0.12.0

What else can I do on Heroku?




EmberJS can not display all content if opened in new tab

If I run my application and click on an image it opens the detail page and show me all content properly. But when I copy the link and paste it on a new tab or right-click an image and open in new tab, I can't see the whole content. What do you think the problem is? This is my twiddle. Thanks

http://ift.tt/20GAz42




Ember. loader giff after action is trigger

I have an Ember app, that after clicking on a selector in a component, it triggers an action that does a transition to the same route(but with now a new value in the url). I'm trying to create a loading giff that is being displayed right when the action is triggered and is being hidden when the component with the new values is updated.

component:

didUpdate() {
 Ember.$('#selectorsBox').removeClass('hidden');
 Ember.$('#spinner').addClass('hidden');
 },
.....

actions: {

  selectFromSelector: function (value) {
   Ember.$('#selectorsBox').addClass('hidden');
   Ember.$('#spinner').removeClass('hidden');

   this.sendAction('selectFromSelector', value);
 }
});

The issue that I'm having is that the app takes some time to load and the giff is not displayed. If I remove the code that is supposed to hide the giff again, I realize that the giff is displayed when the component is rerendered,not when the user selects the option of the selector.

I have also implemented loading substates for transitions for different routes, but I think this may not work for this situation(transitionTo the same route) http://ift.tt/1NPL2ce




Ember - liquid fire - transitions.js

I have installed liquid-fire. Set it all up. And it works between 2 files in the templates folder.

transitions.js

export default function(){
  this.transition(
    this.fromRoute('test1'),
    this.toRoute('test2'),

    this.use('toRight'),
    this.reverse('toLeft')
  );
}

router.js

Router.map(function() {

  this.route('test1', function() {});
  this.route('test2', function() {});

});

application.hbs



test1.hbs

<h1>test1</h1>
<br>
 test 2 

test2.hbs

<h1>test2</h1>
<br>
 back to test 1 

This works fine. I get a nice slide effect between the 2 pages.

But when I move test2 into a folder, no matter what I do, the pages link, but there is no nice transition.

I have tried the below code:

transitions.js

export default function(){
  this.transition(
    this.fromRoute('test1'),
    this.toRoute('cakes.test2'),

    this.use('toRight'),
    this.reverse('toLeft')
  );
}

router.js

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


    this.route('cakes', function() {
      this.route('test2', function() {});
    });

});

test1.hbs

<h1>test1</h1>
<br>
 test 2 

test2.hbs

<h1>test2</h1>
<br>
 back to test 1 

The pages change, so the link works- and you can visit the url cakes/test2 in the browser also. But there is no nice slide transition.




Emberjs: cannot read property 'type' of undefined

I have created a model in my ember app called ticket-stats:

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

export default Model.extend({

    get_tickets_more: attr(),
    get_tickets: attr(),
    get_avg_tickets: attr()

});

The data is pulled from JSON api: http://ift.tt/249fCj1... So i have added a special adapter for this model called ticket-stats:

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

export default JSONAPIAdapter.extend({

    host: 'http://domain.com',
    namespace: 'data',

    pathForType: function(type) {
        return Ember.String.camelize(type);
    }
});

I get the data for this model in route:

import Ember from 'ember';

export default Ember.Route.extend({

    model () {
        var ticketData;
        this.store.query('ticket-stats', { teamID: 218, attUID: 'oc7569', useProd: 1})
                .then(function(stats) { ticketData = stats; });

        return Ember.RSVP.hash({
            currentUser: this.currentUser,
            ticketStats: ticketData
        });
    }
});

And, i get a TypeError:

ember.debug.js:32096 TypeError: Cannot read property 'type' of undefined
    at _pushInternalModel (store.js:1524)
    at push (store.js:1501)
    at finders.js:171
    at Object.Backburner.run (ember.debug.js:678)
    at _adapterRun (store.js:1733)
    at finders.js:168
    at tryCatch (ember.debug.js:53806)
    at invokeCallback (ember.debug.js:53821)
    at publish (ember.debug.js:53789)
    at ember.debug.js:32054onerrorDefault @ ember.debug.js:32096exports.default.trigger @ ember.debug.js:54476(anonymous function) @ ember.debug.js:55727Queue.invoke @ ember.debug.js:333Queue.flush @ ember.debug.js:397DeferredActionQueues.flush @ ember.debug.js:205Backburner.end @ ember.debug.js:560(anonymous function) @ ember.debug.js:1126

Any ideas as to why this is happening? This error goes away when i remove the pathForType function in the adapter, but then i get another error about getting the data from http://ift.tt/1VjQFkk?... which is not the correct URL. I have to convert to camelCase, ticket-stats => ticketStats.

Any help would be appreciated! I'm very new to Ember.




Cannot access what model() hook is returning in controller

i'm quite new to ember and new to Web developement in general.

I'm trying to redirect to a page through an action "Browse" which compares input Title and Keyword with the ones from a "Theme" from the database(Firebase). If they match I can see my page, if they don't I'll throw an error.

Index.hbs

 <div class="jumbotron">
    <div class="container">
    <form>
      <div class="form-group">
        <label for="inputTheme">Theme</label>
    
      </div>
          <div class="form-group">
        <label for="inputKeyword">Password</label>
        
      </div>
    <button class='btn btn-info' >Browse</button>
    </form>
      </div>
    </div>

index.js (Controller)

import Ember from 'ember';

export default Ember.Controller.extend({
  isDisabled: true,

  inputTheme: '',
  inputKeyword: '',    

  actions: {
    browse() {
        this.transitionToRoute("/themes/:theme_id/browse");
    }

  }
});

index.js (Route)

import Ember from 'ember';

export default Ember.Route.extend({
    model()
    {
        this.store.query('theme', {
        orderBy: 'title',
        equalTo: this.get('inputTitle')
      }).then(function(data) {
        return data.get('firstObject');
      });

    }
});

Router.js

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

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

Router.map(function() {
  this.route('about');
  this.route('contact');
  this.route('browse', { path: '/themes/:theme_id/browse'});


  this.route('admin', function() {
    this.route('contacts');
  });

  this.route('themes', function() {
    this.route('new');
    this.route('edit', { path: '/:theme_id/edit'});
    this.route('browse', { path: '/:theme_id/browse'});
  });
});

export default Router;

Theme.js (model)

import Ember from 'ember';
import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
  title: attr('string'),
  keyword: attr('string'),
  master: attr('string'),
  description: attr('string'),

});

The thing is :

1) I don't have any access to "inputTitle" from the route so I can't Query dynamically. Though when I do it the hard way it gets what I need.

2) When I try to access model from my controller it says that there's nothing in it.

What did I miss ?




Ember: Setting a component object value within a promose

I have component with a couple of properties, using a promise in the willRender hook to try and create (pagination) object:

export default Ember.Component.extend({
   pagination:null,
   testing:null // to check if this.set is ok within the promise!
   willRender() {
      let page = {};
      let model = this.get('data');
      model.get('products').then(relatedItems => {

          relatedItems.forEach(function(item,index) {
              // set up the page object here, omitted for brevity
          });
          this.set('testing','hello world');
          console.log(this.get('testing')); // hello world
          this.set('pagination',page);
          console.log(this.get('pagination')); // Object {Prev: "product-1", Next: "product-2"}

      },reject => {
          console.log('error '+reject);
      });
   }
})

In my template

 // prints hello world

However, if I try and access eg , the browser crashes with a loop printing out the object to the console.

I don't know where I'm going wrong here - any help much appreciated!




mercredi 25 mai 2016

store.push not reflecting on template with ember-cli-pagination

I'm new to Ember.js and I'm trying to add an object to the store after an ajax request.

The problem is that it does not reflect on template if I use ember-cli-pagination.

If I use this.store.findAll in model, it works, but when I use this.findPaged it does not.

I'm using ember-inspector and the object appears in the store, just don't in the browser.

My code:

import Ember from 'ember';
import RouteMixin from 'ember-cli-pagination/remote/route-mixin';

export default Ember.Route.extend(RouteMixin, {
  actions: {
    create: function(email) {
      let adapter = Ember.getOwner(this).lookup('adapter:application');
      let url = adapter.buildURL('billing/delivery-files');
      let store = this.get('store');
      let modelName = 'billing/delivery-file';

      return adapter.ajax(url, 'POST', {
        email: email
      }).then(function(data) {
        var normalized = store.normalize(modelName, data.object);
        store.push(normalized);
      });
    }
  },
  model(params) {
    return this.findPaged('billing/delivery-file',params); //does not work
    // return this.store.findAll('billing/delivery-file'); //works
  }
});

Tried the solutions from this issue, and did not work at all.

What am I missing?




How to set a global variable in an ember JS application

Before my Ember application boots, I would like to dynamically set a variable depending the URL:

// Dummy example
if (window.location.hostname == 'awesomewebsite.com') {
  // Set a "global variable" called town
}

I want to have the possibility to rely on that variable to do some stuff afterwards (in a component, template and so on).

What will be the best way to do that ?




disable send button when two conditions aren't met not working in ember.js

I'm trying to create a contact form where the 'Send' button is disabled unless a valid email and a message has been entered. For some reason it's working in the reverse way, when valid email and message entered the button disables. I'm new to ember and cant seem to negate it.

Contact controller

export default Ember.Controller.extend({

email: '',

message: '',

hasValidEmailAddress: Ember.computed.match('email', /^.+@.+\..+$/),
hasEnteredMessage: Ember.computed.notEmpty('message'),

isDisabled: Ember.computed.and('hasValidEmailAddress', 'hasEnteredMessage'),

actions: {

    saveMessage() {
        this.set('responseMessage', `Thank you, your message has been sent. We will get back to you as soon as possible.`);
        this.set('email', '');
        this.set('message', '');
    }
}

});

Contact Template

<div class='row'>

    <h2>Contact</h2>

    <div class='col-md-2'></div>
    <div class='col-md-8'>

        <br/><br/>

        <form>
            <div class='form-group form-group'>
                <label for='email' class=''>Email</label>
                
            </div>
            <br/>
            <div class='form-group form-group'>
                <label for='message'>Message</label>
                
            </div>
            <br/>
            <button class='btn btn-primary btn-default pull-right' disabled= >Send</button>
        </form>

    </div>
</div>

I've tried negating the isDisabled in the template, negating the arguments in the controller both inside and outside of the parenthesis for isDisabled and tried negating the entire line.

Any help would be much appreciated.

Cheers




Ember.js template not iterating over

I have an Ember.js handlebars template running a loop to iterate over a returned store data. There is only one record in the store, so I would expect this code to be executed 1 time. However it is not executing at all and I can't seem to figure out why. Here is the .hbs code:

       
          
            <p class="question">
              
            </p>
            <p class="option">
              Text
              Options

              Add Question
            </p>
          
        

This loop should be rendering data from this query on my store (from my routes .js file for this page):

model(params) {
    var id = params.framework_id;
    return Ember.RSVP.hash({
      question: this.store.query('question', {orderBy: 'framework', equalTo: id}),
      framework: this.store.find('framework', id)
    })
  }

And I know the routing and query of the store is working correctly because the framework I'm trying to iterate on is in the Data store via Ember inspector:

Ember.js Inspector Data

There are other loops on the page (for the "question" store) working without issue. Any thoughts are appreciated




Disabling select option with specific value in Ember

I am using Ember 1.4 and I am having an issue getting a select element(attempt_interval) to be disabled when another select element(max_attempt_count) has a value of 1. It works fine when in my testing environment when not using Ember. Any ideas?

jQuery

$(document).on('change', 'select[name=max_attempt_count]', function(){

    var ctrl=$(this);//$(this) refers to current clicked button
    var maxAttempt =ctrl.closest('form').find('select[name=max_attempt_count]');
    var interval =ctrl.closest('form').find('select[name=attempt_interval]');

    $(maxAttempt).change(function() { //each time a user selects a option (event triggered)
        $(interval).prop('disabled', this.value == 1);
    }).change(); //auto execute when page load
} )

HTML

<select id="ember894" class="ember-view ember-select chosen-select" name="max_attempt_count" style="display: none;">
 <option id="ember907" class="ember-view" value="1">
 <option id="ember908" class="ember-view" value="2"><option id="ember909" class="ember-view" value="3">
 <option id="ember910" class="ember-view" value="4">
 <option id="ember911" class="ember-view" value="5">
</select>




A helper named 'hash' could not be found

I tried to decompose my Ember.js application into different addons. I've moved some of my components to the addon. But at tests of components who use hash helper got the following error:

A helper named 'hash' could not be found

What is the reason and how can I solve it?




How to organize api requests right in Emberjs?

Recently I met with EmberJS. There are a few questions, I can not find answers in the documentation.

  1. Authorized user retrieves data from the server at /api/profile when the page loads. However, if I try to do it through ember api method, I get a request for api/profiles. How to make the right query? I need to get the user structure, save it in 'profile' model and use it in routes and components.

  2. Suppose the first question dealt with. Next there is a problem with the templates. There is root application template. There is "nav-bar" component, which indicates the name of the authorized user. So, how to put the model of user data in this component? This template is not in a route. Here is template so I need to pass user scheme into it.

    <div id = "wrapper">   </div>
    
    

I think maybe i don't get something in architecture of Embers, please help me!

Thank you in advance!




Emberjs store.query returning all records, not those queried

I am trying to query an Ember.js store to retrieve only the records that match my query in a particular column:

model(params) {
    var id = params.framework_id;
    return Ember.RSVP.hash({
      question: this.store.query('question', {framework: id}),
      framework: this.store.find('framework', id)
    })
  }

Unfortunately, the "question" query returns all the records. Within the "question" store, there is a column for "framework". I want to return only the questions that have the framework id that was passed to the request. I've verified the id I'm passing to the query is valid.

The "framework" find is working correctly, only returning one framework based on the id that was passed to the request.

Any help is appreciated!




EmberJS - Relationship not remotly pushed

I have two model with a one to one relation. I only need one direction of the relationship.

App.A = DS.Model.extend({
    b: DS.belongsTo('b', { async: true }),
});

App.B = DS.Model.extend({
    name: DS.attr('string'),
});

Model A is load from the server. Model B is manually pushed using store.pushPayload.

If Model B is loaded before Model A, everything is fine and works correctly inside the template. But when Model A is loaded before Model B, then the name is empty (the whole relation is not set actually).

How can I tell model A that model B was loaded?




ember-data relationships not working

Trying to figure out how to use relationships and it just is not working.

// Data
{
    "apps": {
        "-AFCH5-Kvkc_nfQxnpZ8": {
            "name": "Leap Day",
            "playLink": "http://ift.tt/1WrZtWS",
            "price": "0.00",
            "like": 0,
            "show": "-SFCH5-Kvkc_nfQxnpZ8",
            "provider": "-PFCH5-Kvkc_nfQxnpZ8",
            "imageUrl": "http://ift.tt/1ON9wOi"
        },
        "-AFCH5-Kvkc_nfQxnpZ9": {
            "name": "Gangfort",
            "playLink": "http://ift.tt/1s9NNLs",
            "price": "1.99",
            "like": 0,
            "show": "-SFCH5-Kvkc_nfQxnpZ8",
            "provider": "-PFCH5-Kvkc_nfQxnpZ8",
            "imageUrl": "http://ift.tt/1ONa6LZ"
        }
    },
    "shows": {
        "-SFCH5-Kvkc_nfQxnpZ8": {
            "number": 432,
            "name": "Google I/O Secrets Revealed",
            "date": "05/22/2016",
            "app": ["-AFCH5-Kvkc_nfQxnpZ8", "-AFCH5-Kvkc_nfQxnpZ9"],
            "url": "http://ift.tt/1OI9siP"
        }
    },
    "providers": {
        "-PFCH5-Kvkc_nfQxnpZ8": {
            "firstName": "Steve",
            "lastName": "McLaughlin",
            "nick": "D2d",
            "app": ["-AFCH5-Kvkc_nfQxnpZ8", "-AFCH5-Kvkc_nfQxnpZ9"]
        }
    }
}

Here is the app model import Model from 'ember-data/model'; import attr from 'ember-data/attr'; import { belongsTo } from 'ember-data/relationships';

export default Model.extend({
  name: attr('string'),
  playLink: attr('string'),
  price: attr('string'),
  like: attr('number'),
  show: belongsTo('show', {
    async: true
  }),
  provider: belongsTo('provider', {
    async: true
  }),
  imageUrl: attr('string')
});

Here is the show model

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';

export default Model.extend({
  number: attr('number'),
  name: attr('string'),
  date: attr('date'),
  apps: hasMany('app'),
  url: attr('string')
});

Here is what the ember console looks like

Ember Console

So the problem is when I try to access the show object in my template, its not coming up


    





Emberjs - How to redirect to the last accessed route after session invalidated

We are using ember-simple-auth with cookie authentication and we want to redirect to the last accessed route after we login again when the cookie expires.

We manage to do the redirection for the following scenarios:

  1. Not authenticated and try to access a route from url
  2. Not authenticated and select an item from the navigation menu

Both, after successful authentication, we redirected to the requested route.

But, we want when our session cookie expired and the user tries to access a route to invalidate the session and redirect the user back to authentication page. When the user log in back we want to redirect him to the requested route.

For now we store the previous transition so we can do the redirection but after we invalidate the session the data are lost.

What is the best way to do this?

Our code looks like:

Custom Authenticator

import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';

export default Base.extend({
  restore() {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      let sessionCookie = window.Cookies.get('beaker.session.id');
      if(!window.isUndefined(sessionCookie)) {
        resolve(true);
      }else{
        reject();
      }
    });
  },
  authenticate(data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/login',
        data: data
      }).then((response) => {
        resolve({
          responseText: response
        });
      }, (error) => {
        reject(error);
      });
    });
  },
  invalidate() {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/logout'
      }).then(() => {
        resolve(true);
      }, () => {
        reject();
      });
   });
  }
});

Application Route:

import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
  session: Ember.inject.service('session'),
  beforeModel(transition) {
    if(!this.get('session.isAuthenticated') && transition.targetName !== 'core.authentication') {
      this.set('previousTransition', transition);
      this.transitionTo('core.authentication');
    }
  },
  actions: {
    willTransition(transition) {
      if (!this.get('session.isAuthenticated')) {
        this.set('previousTransition', transition);
      } else {
        let previousTransition = this.get('previousTransition');
        if (previousTransition) {
          this.set('previousTransition', null);
          previousTransition.retry();
        }
      }
    }
  }
 });

Authentication Route

import Ember from 'ember';

export default Ember.Route.extend({
  session: Ember.inject.service('session'),
  actions: {
    login() {
      let that = this;
      let { username, password } = this.controller.getProperties('username', 'password');
      let data = {username: username, password: password};

      if(this.get('session.isAuthenticated')) {
        this.get('session').invalidate();
      }

      this.get('session').authenticate('authenticator:basic', data).then(() => {
        let data = that.get('session.data.authenticated');
        // show response message
      }, (error) => {
        // show error
      });
     }
   }
});




A belongsTo child model from parent model using get method is not of DS.Model type

I am trying to access a related(belongsTo) model from the parent model. the structure is as below

employee= DS.Model.extend({ serialNo: DS.attr('number'), name: DS.attr('number'), address: DS.belongsTo('employee/address') });

Now in a component i am receiving this top level employee model and there i am trying to access address model as below. this.get('employee').get('address')

but the address object i received is not of Model type, so i am not able to call any Model function on it. Surprisingly this.get('employee') returns a model object and i am able to call any Model function using it.

Thanks




cp not updating when using hasMany(..).value() instead of get(..)

I created a jsbin: http://ift.tt/1Wi8CB5

Issue: cp characters on post does not get updated when property content changes on comment.

'Fix': the change does happen when using this.get('comments') instead of this.hasMany('comments').value().

get notifies observers that it should look for changes on the property because it is being used, while hasMany does not seem to have this functionality..

Is this on purpose or a bug?




Obtaining related Ember model data from within a route or component

I have a (product category) model with a many to many relationship eg

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

My category route (product.items) is backed by this model, and it's no problem displaying the related product data:


 


However, I need to obtain the related data within the child route (product.items.item). The model hook for the route looks like this:

model(params) {
  let parentModel = this.modelFor('product.items'),
  let model = this.store.findRecord('product',params.id);

  return Ember.RSVP.hash({
    data:model,
    parentData:parentModel
  });
}

I can then then pass this model to a component.

What I am trying to do is access that related within a component (or within the route). Assuming the model is available in the component as parentModel I can access the name of the parent category as

 let name = parentModel.data.get('name');

I thought I could do the same for the related products ie

 let products = parentModel.data.get('products');

However, this doesn't return anything. Am I making a basic mistake here?

The reason I want to access the other products in the parent category, when viewing an item, is that I want the user to paginate through each item.

Using the JSONAPIAdapter.

Many thanks in advance!




Preserve scrolling position in emberJS

I'm using ember v2.5.0. I want my images page to scroll me where I was before going to details page when I hit the "back" link.

I found this about the problem :

http://ift.tt/1szESD1

But when I try to include it in my project, it gives me error

routes/index.js: line 130, col 29, 'opts' is defined but never used.
routes/index.js: line 154, col 13, 'position' is defined but never used.
routes/index.js: line 155, col 13, 'viewportHeight' is defined but never used.

Also, in the code it says ThingsView at the end and I dont know what to write there because I'm using a list not a view.

This is my twiddle :

http://ift.tt/1WNVXWn

Can anyone help me integrate this into my project or offer me something else? I'm stucked with this. Thanks.




Ember - Object property observers

It seem like I can't use arrow functions as observers, anonymous methods works fine. Am I missing something crucial, why does the context differ?

ember.debug.js:32096 TypeError: _this3.get is not a function
    at .sessionChanged (session.js:77)
    at Object.applyStr (ember.debug.js:23331)
    at Object.sendEvent (ember.debug.js:16842)
    at ObserverSet.flush (ember.debug.js:20171)
    at endPropertyChanges (ember.debug.js:20682)
    at Object.changeProperties (ember.debug.js:20707)
    at Object.setProperties [as default] (ember.debug.js:21786)
    at exports.default._emberMetalMixin.Mixin.create.setProperties (ember.debug.js:35465)
    at invalidate (session.js:98)
    at session.js:42

Anonymous function - Works.

  /**
   * Session event observer.
   */
  sessionChanged: Ember.observer('user', function() {
    // Get the user value
    const user = this.get('user');

    // Get the session token
    const token = this.get('token');

    console.log(user, token);
  }),

Observer method using arrow function - Throws exception.

  /**
   * Session event observer.
   */
  sessionChanged: Ember.observer('user', () => {
    // Get the user value
    const user = this.get('user');

    // Get the session token
    const token = this.get('token');

    console.log(user, token);
  }),




How do I use ember-cli with the LTS release channel?

I would like to update an addon to the long term support release channel using ember-cli. How do I do this?




Reloading just one model using RSVP in Ember

To load many data models into a route on the model hook you need to use RSVP so I'm doing this:

export default Ember.Route.extend( {
  model( params ) {
    return Ember.RSVP.hash( {
      cars: this.store.query( "car", params ),
      stats: this.store.findRecord( "shop", 1 ),
    } );
  }
} );

The problem comes in that stats is always going to be the same but using queryParams I will change the cars list. Setting queryParams as:

queryParams: {
  color: {
    refreshModel: true,
  },
}

will call the model hook (as intended) but it will reload both models, cars and stats, when I'm only interested in refreshing cars.

Is there a way, with or without RSVP, to load both models on entry but only update one of them when queryParams change?




How to hide data in source view from drop down list (Ember Javascript)

I am currenty working on building a customer management system.

The website is coded using embers framework.

I have a drop down list with a list of names which relate to their ID - this can be seen in the source view, what is the easiest method/solution to hide this data?

I have included the section of code below, thank you in advance for any guidance or tips.

<html>
<head>
<link rel="stylesheet" href="css/styles.css" />

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,700">
  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat">
  <link rel="stylesheet" href="http://ift.tt/1NLUTj9">
</head>


   <p class="asset-search__stacked">
        <br>
        <div  class=" group-selector group-selector--condensed">
          <p>
            <label class="form__label">
              Group:
<select  class=" ember-select form__select">
<option  class="" value="*">Please select</option>
<option  class="" value="462">.Test Group</option>
<option  class="" value="334">7.5 Tonne Vehicles</option>
<option  class="" value="277">A &amp; B Lewis</option>
<option  class="" value="2221">A M Lloyd</option>
<option  class="" value="2551">Adrian CVH</option>
<option  class="" value="2719">Adrian Scipps Ltd</option>
<option  class"" value="3314">Lifting Systems Ltd</option>
<option  class="" value="4343">Lloyds Coaches</option>
<option  class="" value="1592">London Master Services Ltd</option>
<option  class="" value="3815">M &amp; P Enterprises Ltd</option>value="2256">W M Rose</option></select>
</label>
            <button type="button" class="button button--icon group-selector__button" disabled="disabled"  >
              <i class="fa fa-chevron-up"></i>
            </button>

</html>




mardi 24 mai 2016

Sending data from backend to Ember.JS

anybody knows is it possible (and how to achieve that) to send some data from backend to Ember.JS, but communication should be initialized by backend?




Can an Ember Addon be in a pods structure?

I'm trying to separate some components from our application into an addon. Application is in pod structure. So when I move codes from application to addon, I got:

Could not find module <addon's addon directory> imported from <addon's app directory>

But when I reorganize codes as not using pod structure, it works.

So, how can I continue to use POD structure in an addon?

Note: adding "usePods":true to .ember-cli doesn't make any sense.




EmberJS - testing input action on enter

I have an EmberJS (2.5.0) component similar to the following:



Basically, hitting enter on the input field should trigger the 'handleSearch' action. And in my component, so far I have this:

searchValue: null,
actions: {
  handleSearch() {
    var searchValue = this.get('searchValue');
    var submitSearch = this.get('submitSearch');
    console.log('Search term entered: ', searchValue);
    if (submitSearch) {
      submitSearch(searchValue);
    }
  }
}

And the component is called via:



That all works fine and all, but I'm having trouble actually testing it.

Here's my integration test (pseudo-copied from the guide):

test('search input', function(assert) {
  this.set('externalAction', (actual) => {
    console.log('in external action');
    assert.equal(actual, 'hithere');
  });
  this.render(hbs``);
  this.$('input').val('hithere');
  this.$('input').change();
});

The problem is, my handleSearch action handler never gets triggered. So how do I get my input field to trigger the handler in my integration test? I've also tried this.$('input').submit() and this.$('input').trigger('change'), but neither seems to do anything.




ember js query param alphabetical order

I current have a link as below in xyz page i.e. #/xyz:

<a href="#/abc/def?zqp=2&bpq=1">Random Text</a>

Upon clicking this I go to

#/abc/def?bqp=1&zqp=2

Can you observe that order of query params has changed from

zqp=2&bpq=1 to bqp=1&zqp=2

I believe this is because ember js takes the query param as per alphabetical order

Now in bqp=1&zqp=2 when I press back I dont go to xyz instead I go zqp=2&bpq=1 with an error saying undefined route.

How to prevent this apart from re-ordering the query-params?




Ember-cli how to change input path of files

I am new to ember. But for a particular task i need to change input path of templates to compile. i.e default is app/templates. but i want to change this path. I have read the ember-cli-build.js file but i can edit only output path. how can i edit the input path. My ember-cli-build.js

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
    outputPaths: {
      app: {
        html: 'ember_build_index.html'
      }
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

app.import('bower_components/bootstrap/dist/js/bootstrap.min.js');
app.import('bower_components/bootstrap/dist/css/bootstrap.min.css');
app.import('bower_components/bootstrap/dist/css/bootstrap.css.map');
  return app.toTree();
};