lundi 31 août 2015

Setting property for class name binding

I'm having some trouble getting my class name binding to properly change the class on a div based on a property that either returns true or false.

export default Ember.Route.extend({
  isConnected: function() {
    return false;
  }.property(),
  actions: {
    var self = this;
    [some ajax action]
    success: function(data){
      self.set('isConnected', true);
    }
  }
  ...
});

And in the template I have the typical class name binding setup

<div class="progress">
  <div class="progress-bar {{if isConnected 'progress-bar-success' 'progress-bar-danger'}}" style="width: 101%;"></div>
</div>

It doesn't seem to be working, and I'm getting no errors




EACCES issue, When i am installing ember-cli

When i'm installing ember-cli with this command "npm install -g ember-cli" showing this error in terminal.

npm ERR! Error: EACCES, mkdir '/usr/lib/node_modules/ember-cli'
npm ERR!  { [Error: EACCES, mkdir '/usr/lib/node_modules/ember-cli']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/lib/node_modules/ember-cli',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/lib/node_modules/ember-cli',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack: 
npm ERR!    [ '/usr/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23',
npm ERR!      '/usr/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53',
npm ERR!      'Object.oncomplete (fs.js:108:15)' ] }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.13.0-48-generic
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "-g" "ember-cli"
npm ERR! cwd /home/narayand4
npm ERR! node -v v0.10.37
npm ERR! npm -v 1.4.28
npm ERR! path /usr/lib/node_modules/ember-cli
npm ERR! fstream_path /usr/lib/node_modules/ember-cli
npm ERR! fstream_type Directory
npm ERR! fstream_class DirWriter
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/usr/lib/node_modules/ember-cli'
npm ERR! fstream_stack /usr/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23
npm ERR! fstream_stack /usr/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53
npm ERR! fstream_stack Object.oncomplete (fs.js:108:15)
npm ERR! Error: EACCES, open 'npm-debug.log'
npm ERR!  { [Error: EACCES, open 'npm-debug.log'] errno: 3, code: 'EACCES', path: 'npm-debug.log' }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.13.0-48-generic
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "-g" "ember-cli"
npm ERR! cwd /home/narayand4
npm ERR! node -v v0.10.37
npm ERR! npm -v 1.4.28
npm ERR! path npm-debug.log
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, open 'npm-debug.log'
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/narayand4/npm-debug.log
npm ERR! not ok code 0

please suggest me what i doing wrong?




Ember.js: how to pass model to a template

I'm testing Ember.js and I have a very trivial problem. I want to show in Handlebars Template an input text with the value of a variable called 'test' with value 'This is a test'

The problem is that input is empty as well as h1 element although the varibale has a value

This is file routes/index.js

export default Ember.Route.extend({

    model : function(){
        return { test:'This is a test'}
    },

    /* Default Implementation */
    setupController: function(controller, model) {
        controller.set('model', model);
    }

});

This is file templates/index.hbs

{{input value=test type="text" }}

<h1>  {{test}} </h1>

This is file router.js

Router.map(function() {

this.route('index', { path: '/' });

});

Where is the error? Thanks in advance




ember cli build fingerprinting external URL?

I have this route podcasts. The model hook calls getJSON to a url on a different domain. When I build for production, ember-cli seems to think this is an asset and fingerprints it like so:

http://ift.tt/1hsC0Cj

I tried adding it to the exclude property in the fingerprint option in ember-cli-build.js, but I seem to get the same result. I tried the full URL as well.

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
    fingerprint: {
      exclude: ['datafruits.json']
    }
  });

Yes my app is called "datafruits" if that has anything to do with it. Here is the aforementioned podcasts route:

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    willTransition: function(transition) {
      Ember.$("#podcastsModal").modal('hide');
    }
  },

  setupController: function(controller, model){
    this._super(controller, model);
    Ember.run.schedule('afterRender', this, function () {
      Ember.$("#podcastsModal").modal('show');
      var _this = this;
      Ember.$("#podcastsModal").on('hidden.bs.modal', function () {
        console.log("modal exited");
        _this.transitionTo('application');
      });
    });
  },

  model: function(){
    return Ember.$.getJSON('http://ift.tt/1if02Bs')
    .then(function(data){
      return data.podcast;
    });
  }

The rest of my ember-cli-build.js:

/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var ES6Modules = require('broccoli-es6modules');
var esTranspiler = require('broccoli-babel-transpiler');
var mergeTrees = require('broccoli-merge-trees');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
    fingerprint: {
      //prepend: "//datafruitstest.s3-website-us-east-1.amazonaws.com/",
      exclude: ['datafruits.json']
    }
  });

  // 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(app.bowerDirectory + '/bootstrap/dist/js/bootstrap.js');
  app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.css');
  app.import(app.bowerDirectory + '/moment/moment.js');
  app.import(app.bowerDirectory + '/fullcalendar/dist/fullcalendar.css');
  app.import(app.bowerDirectory + '/fullcalendar/dist/fullcalendar.js');
  app.import(app.bowerDirectory + '/jplayer/dist/jplayer/jquery.jplayer.js');
  app.import(app.bowerDirectory + '/jsTimezoneDetect/jstz.min.js');
  app.import(app.bowerDirectory + '/emojione/assets/css/emojione.css');
  app.import(app.bowerDirectory + '/emojione/lib/js/emojione.js');
  app.import(app.bowerDirectory + '/autolink/autolink.js');

  var phoenixTree = "./vendor/phoenix";
  var phoenixAmdFiles = new ES6Modules(phoenixTree, {
    format: 'amd',
    esperantoOptions: {
      strict: true,
      amdName: "phoenix"
    }
  });
  var phoenixTranspiledFiles = esTranspiler(phoenixAmdFiles, {});

  return mergeTrees([app.toTree(), phoenixTranspiledFiles]);
};




EmberJs Async Firing Immediately

We have a model that has a number of belongsTo and hasMany relationships set as async: true. The API is passing down IDs only. As soon as the page loads Ember makes request for all of these IDs.

Is this intended behavior? I was under the impression this data would be loaded when called.

How would I go about figuring why these calls are happening?

We are using Ember 1.13.9 and Ember-data 1.13.11




How to access server that isn't localhost?

Thats what I do:

sudo npm install -g ember-cli
ember new my-app
cd my-app
ember server

If I access this server from another computer from LAN with a web browser I get some 'Content Security Policy' warnings and nothing works.




Communication between components and routes in emberjs 2.0?

I have two models in my route, people and appointments.

My components are: people-list(parent) and people items(children), appointment-list(parent) and appointment items(children).

In my route, I want to list appointments based on checked people (checkboxes in each people item). How would I tell my route about all the checked people items?

Also, I have a datepicker on the route, I want to display appointments based on date, how would I go about doing this?

Again, I want to use pure COMPONENTS, no controllers and I also do not want to make a property in my people model called isChecked as this would never be a real attribute in a real database table.

Help is greatly appreciated. Thanks.




Calling Map on a model object not returning anything

I am having an issue with transforming my model object in an Ember application.

I have a calendar route which defines a model like so.

this.store.findAll('competency');

I am trying to transform the data returned from this in a controller method calendarItems which is defined as a property.

What I would like to do is take my model and call the map function on it, transform the object and return it back as a property.

I have changed the controller to a ArrayController to allow Enumberable methods to be called but still no luck. The function is present when I can this.get('model').map

Any ideas where I am tripping up? Maybe my approach is way out but basically I just want to transform am model and present that data to the template.

Thanks in advance! Ryan




Save belongsTo change in model not part of Payload

I'm trying to save a change to a parent model on a child model in Ember to my server, but for some reason the REST Payload doesn't contain the belongsTo Relationship

My 2 models are defined like this:

parent.js

import DS from 'ember-data';

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

child.js

import DS from 'ember-data';

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

when I change the belongsTo to a different parent for a childModel by editing and saving an existing record. Somehow my payload doesnt include the parent model.

For example.

I have a child like this:

{
    id: 1,
    parent: 1,
    childName: "Child 1"
}

and in code I do this:

childModel.set('parent', parentModel); // this is a different parentModel, one with id: 2

I would expect the payload to look something like this:

HTTP-PUT: http://server/child/1

{
    id: 1,
    parent: 2,
    childName: "Child 1"
}

however, in reality, the payload is this:

HTTP-PUT: http://server/child/1

{
    id: 1,
    childName: "Child 1"
}

What goes wrong here? Why is the parent relationship missing from the payload?

Some extra information:

  1. Ember v2.0.1
  2. Ember-data v2.0.0
  3. Relationships must be async: true (which is the default)
  4. I'm using a standard DS.JSONAPISerializer in combination with the DS.RestAdapter



Component Property available to all Views Ember?

I want GoogleMap markers and Map object available to all views, is it possible to access google-map component property available to views? or maybe it is a design fault, and someone can suggest a better solution.

Here is the scenario,

  1. I have a google map with several markers, which when I hover over pops up the infoBox.
  2. Now I want this InfoBox to be open whenever I hover over the same data outside map.

I have two floating divs, one having GoogleMap and the other having data in it.




Ember session initializer causing page reload for every route

I'm building a Twitter based app in Ember-CLI and have a session initializer to ensure users are authenticated on each route. Users login via Twitter using the passport-twitter module for Express.js. I've done this before in a previous app and it's fine, but in this app I've noticed that every route reloads the page.

I've stripped everything out to just an h1 tag per route and it still reloads the page. As soon as I remove the initializer and beforeModel hook below however, everything works as expected with no page reload.

initializers/session.js :

name: 'session',
initialize: function(container, app) {
  var Session = Ember.Object.extend({
    user: null,
      isAuthenticated: function() {
      return this.get('user') !=null;
    }.property('user')
  });
  app.register('session:main', Session);
  app.inject('route', 'session', 'session:main');
  app.inject('controller', 'session', 'session:main');
}

routes/application.js

beforeModel: function() {
  var route = this;
  var promise = this.store.find('user', {operation: 'authenticated'});
  return promise.then(function(users) {
    if (users && users.get('length') > 0) {
      var user = users.get('firstObject');
      route.set('session.user', user);
    }
    return users;
  });
},

I've tried setting {singleton: true} in app.register just in case, but that doesn't work either.

I'm using a more recent version of Ember 1.11.1 and Ember-CLI 0.2.3 and I'm not sure how to even debug this. Any help much appreciated.




How do I make use of libraries in my Ember unit tests?

I'm trying to make use of a library (chance.js) in my Ember unit tests, but I can't seem to import it in my tests.

So far I've tried using NPM (with and without ember-browserify), Bower (played around with trying the app.import calls in ember-cli-build.js.

No matter what I do, I can't seem to be able to access the chance functions/module.

Any help would be greatly appreciate. Top marks would go to anyone who can point me to an Ember project which is using chance.js in their unit tests.

If possible in your answer, a brief explanation of which dependency management is appropriate would be very helpful. From what I've read, it seems NPM might be the go-to as the Ember project is looking to move away from Bower, see here.

Also, if anyone knows of any helpful articles (up-to-date would also be a plus), feel free to mention them in comments.

Thanks!




Is there anything like ruby's .send in HTMLBars or Handlebars?

Was wondering if there's anything like ruby's .send for htmlbars. Been trying to search for it, but can't seem to find a proper answer. Here's what I want to do:

{{"name-of-helper" arguments}}

As simple as this. Is there any trick under it to achieve this effect?




ember-data reload model in route to sideload relations (only if they are missing)?

My app has an index page listing all items, when clicking an item I want to reload the model for that item, as the single-model API endpoint sideloads the relations.

But I only want to reload the model if but only if they aren't already fetched.

Is there any way to achieve this? I've tried something like:

return this.store.find('todo-list', params.id).then((model) => model.reload());

but that didn't seem to work + it will always reload regardless of the relations already being loaded.




Should I have to use ember - cli to use version ember 1.10.0?

I'm running my app using Ember App Kit, version 1.9.1. If I want to move to ember version 1.10.0 I have to upgrade to ember-cli?




How to have both observer and on init for ember js properties

New ember rules states that we need to use the below pattern

propObserver: Ember.observer(function () {
   //code
})

instead of

propObserver: function() {
    //code
}.observers('someProp')

Before updating ember we could do the below

propObserver: function () {
    //code
}.observes('someProp').on('init')

How to achieve this cascading?

Now i know we can do this separately

propObserver: Ember.observer('someProp', function () {
   //code
})

propObserver: Ember.on('init', function () {
       //code
})




Uncaught TypeError: Cannot read property 'enter' of undefined , while using transitionToRoute

I am getting an "Uncaught TypeError: Cannot read property 'enter' of undefined". This is when i am using transitionToRoute in a controller. The transitionToRoute function in controller,

     transitionToRoute: function() {
         // target may be either another controller or a router
         var target = get(this, 'target');
         var method = target.transitionToRoute || target.transitionTo;
         return method.apply(target, arguments);
     },

here the target variable is being assigned a view instead of controller or router. I don't know if this is a issue or am i using transitionToRoute in a wrong way. Need help here.




dimanche 30 août 2015

Add Ember Data query helper method

I'm using Ember API with a JSON API backend. The API accepts filters like this:

/users?filter[simple][name]=John

Right now, whenever I want to make a query, I'm doing this:

this.store.query('users', {
  filter: {
    simple: {
      name: 'John'
    }
  }
});

It would be nice to avoid this verbosity by adding a helper function that works like this:

this.store.simpleQuery('users', { name: 'John' });

That function would pass its arguments directly to query(), just wrapping the query in { filter: { simple: ... } }.

Is this possible? How do I do this?




Need example on implementing Ember.js 2.0 RESTful API Authentication

Can someone please provide example on Ember.js 2.0 RESTful API Authentication? thanks




Ember.js action bubbles up and skips a route

Setup

Imagine an Ember.js app (tried v1.13.9) with this structure:

  1. ApplicationRoute
  2. IndexRoute
  3. IndexController

On the index template, there's simply a button with an action:

<!-- index/template.js -->
<button {{action 'ping' 'index template'}}>index</button>

All routes/controllers handle this action, printing out a message and passing the action up until it reaches ApplicationRoute. Eg, for IndexRoute it is:

// excerpt from index/route.js
actions: {
  ping(from) {
    console.log('IndexRoute^ping from', from);
    return true;
  }
}

This same action can also originate at IndexController:

// excerpt from index/controller.js
thingsHappen() {
  this.send('ping', 'index controller');
}

You can see the code and play with it at these URLs:

Question

When you press the button, the messages show that the action is seen by all three routes/controllers, in order, from the inside bubbling up. However, when the action is sent from IndexController, it skips IndexRoute. Why is this?




Ember: Get the value of textarea from route

I want to get the value of the textarea to use inside my route. I tried using the method below, but the alert shows 'undefined' for that value. How would I go about getting the value of the textarea from the route? I am running the latest version of ember-cli.

Template

{{textarea type="text" value='name'}}
<button {{action 'submit'}} >Send</button>

Route

actions: {
    submit: function() { alert(this.get('name'));
    }   }




Non-enumerable properties

all instances of Ember.Object has non-enumerable properties that start with double underscores like __ember_meta, __next_super, __proto__ and so forth.

They are defined like this

 export var META_DESC = {
  writable: true,
  configurable: true,
  enumerable: false,
  value: null
};

var EMBER_META_PROPERTY = {
  name: '__ember_meta__',
  descriptor: META_DESC
};

//....

obj.__defineNonEnumerable(EMBER_META_PROPERTY);

And I have an Email value object, on which I tried to replicate this technic

// lib/validatable-object.js
import Ember from 'ember';

const SKIP_VALIDATION = {
  name: '__skipValidation',
  descriptor: {
    writable:     true,
    configurable: true,
    enumerable:   false,
    value: null
  }
};

export default Ember.Object.extend({
  init: function() {
    this.__defineNonEnumerable(SKIP_VALIDATION);
    this._super(...arguments);
  }
});

and within initialization (inside init) everything looks correct

Object.keys(this)
["address", "label"]
Object.getOwnPropertyNames(this)
["__ember1440930504837", "__nextSuper", "__ember_meta__", "address", "label", "__skipValidation"]

but not later, when I try to save a model with array of the emails - __skipValidation is enumerable again :(

// inside serialize() function
Object.keys(snapshot._attributes.emails[0])
["address", "label", "__skipValidation"]
Object.getOwnPropertyNames(snapshot._attributes.emails[0])
["address", "__nextSuper", "__ember1440931027338", "validLabel", "label", "__skipValidation", "__ember_meta__", "validAddress"]

How to prevent property from becoming enumerable again?




How do I customise the Ember store path for a specific model?

I have an API endpoint at /movies/:movie_id/actors.

I'm trying to use Ember Data to fetch this endpoint. I'm not interested in modelling movies at this point, just actors. My route looks like this:

this.route('actors', { path: '/movies/:movie_id/actors' });

My actor model is plain:

DS.Model.extend({
  name: DS.attr("name")
})

In my actors route, I have:

model: function(params) {
  // params contains movie_id
  return this.store.findAll('actor')
}

This will cause Ember to send a request for /actors. How can I tell Ember to send a request to /movies/:movie_id/actors instead?

My JSON is being returned in the format { "movies": [ { … } ] } and I'm using the DS.ActiveModelAdapter, if that's at all relevant. I'm using Ember 2.0.




samedi 29 août 2015

How to find out size of used libraries in Ember-cli project?

suddenly the application come too big and I started to wonder how to find out what libraries has biggest size?




how to get a flexible Ember.js parent layout

In an Ember template structure with {{outlet}}s, the way to organize layouts is generally like this:

resource.hbs
  - index.hbs
  - child.hbs

In other words, if I want to use an {{outlet}} to render templates from child routes, I also have to have an index child route that sits in the outlet when at the top level resource route.

Example:

<section id="layout">
  Some layout content
</section>

{{outlet}}

Is there a way to not render anything in the {{outlet}} when I'm in the parent resource route?

My use case is that, in the example above I want section#layout to be width: 100%;, but when in a child route, and the outlet has content, I want section#layout to be half the width.

This may be possible to do with some clever CSS, but I'm thinking I'll need to bind a className to the current route name for this to be possible.




Emberjs - using computed property

This is what I have in template:

{{check-box isChecked=hasPhoneForSecureAlerts visibleLabelLoc=".t.settingscontact.label.phone" class="checkbox-inline narrow" testId="chk-phone"}}

This is what I have in controller for this property:

hasPhoneForSecureAlerts: Em.computed.bool('securePreferences.phoneLocalNumber'),

Let's assume, that originally this property is set to true and check box is checked, If I uncheck check box, this property is set to false and actually does not correspond to state of securePreferences.phoneLocalNumber.

To set it to initial value, when we are leaving this screen without saving, I just use in resetController at corresponding route:

controller.set('hasPhoneForSecureAlerts', controller.get('securePreferences.phoneLocalNumber') !== null);

Is this code correct? It actually works fine, but I am finding anywhere in Emberjs documentation something like that. Thanks!




Ember service property with promise data

I have a service to get the current user and it returns correctly when I return a hardcoded object, but I can't get it to return data from an ajax call.

export default  Ember.Service.extend({
  currentUser: Ember.computed(function() {
    Ember.$.ajax({
      url: "http://localhost:8000/v1/me/"
    }).then(function(data){
      console.log(data);
      return data;
    },
    function(err){
      console.log(err);
    });
  }),
});

I know the data is being returned correctly, according to the console.log in the promise.

When I use this service in a controller, it is returning nothing for the currentUser, however I know everything is hooked up correctly because if i substitute an Ember.Object in for the ajax query, it returns that object to the Controller.

Do I need to do something special with the property that contains the ajax query to be able to use the returned data in a controller?




Torii session undefined - not injected in ember / firebase app

In an ember cli project using firebase, I've installed (using ember install) emberfire and torii. I have put the following configuration in my config/environment.js right after my firebase app url:

torii = {
  sessionServiceName: 'session',
}

And I've put an adapter into app/torii-adapters/application.js:

import Ember from 'ember';
import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';

export default ToriiFirebaseAdapter.extend({
  firebase: Ember.inject.service()
});

However, when I try to get torii's session variable on any route or controller:

this.get("session").fetch().catch(function() {});

the session is undefined:

Error while processing route: app Cannot read property 'fetch' of undefined TypeError: Cannot read property 'fetch' of undefined

I've followed the firebase docs/examples to the best of my knowledge, so I'm not sure what I'm missing. Is another step needed to have torii inject the session variable into all routes and controllers?


The versions in my stack are:

Ember-CLI: 1.13.7
Firebase (package.json): 2.2.9
EmberFire (package.json): 1.5.0
Torii (package.json): 0.5.1

NOTE: I currently have firebase itself working great—all of my models are in sync—so it is not likely the result of a faulty firebase setup. Also, this.get('session') returns undefined anywhere in any route or controller in my app.




ember-cli with rails-api app working in localhost but not in heroku

I'm using the rails-api gem to generate api for my app and using Ember-cli, pretty much the same setup as here :

http://ift.tt/18xl3mf

I did, however, namespace my api by using scope in routes.rb like so:

scope '/api' do 
    root 'teachers#index'
    resources :teachers, except: [:new, :edit]
    ...   

  end

Now, when I do

ember server --proxy http://localhost:3000/api/

my app works on localhost.

I then deployed both applications to heroku: the rails to, say, backend.herokuapp.com and the ember-app to frontend.herokuapp.com

I used this buildpack:

http://ift.tt/1pWW3b7

and as per the instructions there, used

heroku config:set API_URL=http://ift.tt/1LJdeLJ

and

heroku config:set API_PREFIX_PATH=/api/

Yet when I go to frontend.herokuapp.com, my data never loads. It shows up as json on backend.herokuapp.com clearly, but when I try and load my frontend.herokuapp.com, I get this error:

SyntaxError: Unexpected token <
    at Object.parse (native)
    at ie.parseJSON (http://ift.tt/1Jp8QLT)
    at q (http://ift.tt/1LJdkmh)
    at r (http://ift.tt/1Jp8QLV)
    at XMLHttpRequest.t (http://ift.tt/1LJdhXE)

This error never shows on the development side.

Then, when I try to create a new Teacher using the ember interface, I get this error:

POST http://ift.tt/1Jp8QLX 405 (Not Allowed)

What is causing these errors? How do I get my ember app to communicate with my rails-api app on Heroku?




Computed property in controller based on route's model in EmberJS

I want to implement computed property in controller that changes when data in route's model changed.

Route:

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return new Ember.RSVP.hash({
            ingredients: this.store.findAll('ingredient'),
            recipes: this.store.peekAll('recipe')
        });
    },

    setupController: function(controller, modelHash) {
        controller.setProperties(modelHash);
    }
});

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
    pageNumber: 0,
    pageSize: 16,

    pages: function() {
        var pages = [];
        if (this.model != null) {
            var content = this.model.recipes;
            while (content.length > 0) {
                pages.push(content.splice(0, this.get("pageSize")));
            }
        }
        return pages;
    }.property('model.recipes.@each', 'pageSize'), 

    recipesOnPage: function() {
        return this.get('pages')[this.get('pageNumber')];
    }.property('pages', 'pageNumber')
});

This code produce no error, but doesn't work - "pages" always empty. And "pages" property doesn't recomputed on model changing. What am I doing wrong? And how to achieve desired result?

P.S. Ember version - 1.13.




Ember - Transition to same route with same model

I have a left tree list, and each item in the list opens same route with different model. What i want is, if i click on the same item again and again, i want the route to load again. I know ember doesn't normally function this way. Are there any tweaks to achieve this?




vendredi 28 août 2015

How to save Ace editor's content in Ember.js

I made an Ember.js component based on Ace Editor.

This component's is called from a mytemplate.hbs template like this:

{{ace-editor value=model.my_string_field}}

The template for the component itself being ace-editor.hbs:

<div id="ace-editor">{{value}}</div>

And the component's controller ace-editor.js:

import Ember from 'ember';

export default Ember.Component.extend({
    setAceEditor: function(){
        // usual ace-editor setup stuff
        this.editor = ace.edit('ace-editor');
    },

    didRender: function(){
        this.setAceEditor();
    },

    actions: {
        save: function(){
            this.sendAction('save')
        },
        submit: function(){
            this.sendAction('submit')
        }
    }
});

In mytemplate.hbs, the component is wrapped into a form with a submit button. If I put a simple textArea in place of this component, everything works fine and the value is saved on submit.

However, if I use this component, the value of model.my_string_field is correctly displayed and editable in the Ace editor, but no change gets saved on submit.

I noticed that the textArea created by Ace editor doesn't have an ember id so I must be missing something on how to bind this text area to the model.




Ember error while processing route: You must use Ember.set()

I can't understand what is the reason of this error (EmberJS 2.0):

Error while processing route: articles.index Assertion Failed: You must use Ember.set() to set the `content` property (of <DS.RecordArray:ember379>) to ``. EmberError@http://ift.tt/1PDvYtU

My route is looks like:

App.ArticlesRoute = Ember.Route.extend({
  model: function() {
    return this.store.findAll('article').set('content', '');
  }
});

and model like:

App.Article = DS.Model.extend({
  title: DS.attr('string'),
  body: DS.attr('string')
});

App.Article.FIXTURES = [{
  id: 1,
  title: "My article",
  body: "Some text"
}];

Сan anyone help me?




Integrating ember-modal-dialog inside a site header Ember 2.0

I'm very new to the Ember framework and I have a question regarding getting a modal setup. I have the site-header as a component. When I click a login button I'd like for a modal to popup. I found the Ember Modal Dialog plugin and was able to set it up so that there is a modal always shown in application.hbs. However, I'm having trouble understanding a couple of things but first here are my files.

application.hbs

{{site-header}}
{{outlet}}
{{#if isShowingModal}}
  {{#modal-dialog close="toggleModal"
                  alignment="center"
                  translucentOverlay=true}}
    Oh hai there!
  {{/modal-dialog}}
{{/if}}
{{site-footer}}

site-header.js

import Ember from 'ember';

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

So, I have this code for the button in my site-header.hbs:

<li class="login-button"><button class="btn btn-block btn-danger" {{action 'toggleModal'}}>Login</button></li>

As I understand it, action is saying to find toggleModal property in the site-header.js and execute the function above which does the property toggling.

  1. However, how does application.hbs "see" the value of isShowingModal? Can it even see that value since the modal isn't showing up?

  2. When most developers have modals, do they all go inside application.hbs since you want them to appear in the middle of the screen {{outlet}} area? How can you improve the process for including multiple modals?

  3. What changes should I make to make the modal show up when the user clicks a button in the header?




Respond to data changes in a component

I’m trying to build a component that draws a Highcharts graph and struggling to get it to run a function in response to data changing. Here's the closest I've come so far, though I'm not sure if I'm thinking about this the right way:

// Template using the component:
<script type="text/x-handlebars" data-template-name="index">
  {{overview-chart data=model.dateRangeContributionSummary}}
</script>


// Component Template:
<script type="text/x-handlebars" data-template-name="components/overview-chart">
  <div class='chart-wrapper clear'>
    <div id='total-chart-inner' class='chart-inner'>
      {{chart}}
    </div>
  </div>
</script>


// Component JS code:
app.OverviewChartComponent = Ember.Component.extend({

  loadInitialChart: function() {
    this.send('drawGraph');
  }.on('didInsertElement'),

  chart: function() {
    if (Ember.$("total-chart-inner").exists()) {
      this.send('drawGraph');
    }
  }.property('data.totalSeries', 'data.totalCategories'),

  actions: {
    drawGraph: function() {
      // Code to draw Highcharts graph goes here...
    }
  }
});

I'm using Ember v1.10.0, not sure if that's hurting me at all. Ideally I wouldn't need loadInitialChart, but the chart function is initially called before the template has been written to the DOM. And then the biggest problem is that chart isn't called again when my data changes. Any hints as to what I might be getting wrong, or a better approach?




Django not recognizing my Token?

I'm using Django Rest Framework on the backend and an ember-cli app on the frontend. The authentication is working correctly, but there seems to be a hole somewhere in authorization.

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}

# views.py
class CurrentUserView(APIView):
    "get the data for the current authenticatd user"
    permission_classes = (IsAuthenticated,)

    def get_queryset(self, request):
        queryset = User.objects.filter(username=request.user.username)
        return queryset

    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

When I make a request to this endpoint /v1/me/ it responds back with a 403. When I take off the permission class, I get back {"id":null,"username":"","is_active":false} because it doesn't know who I am.

Also, when I use the browsable API, the /v1/me URL works correctly.

On the Ember side of things, I login with my account and correctly get back my Token. In the request the Authorization: Token asdf1234asdf1234asdf1234 is being passed. I would think Django takes that token and knows who I am? Am I missing something?




Emberjs: Use Websocket backend as data source

I am fairly new to ember.js and client side development in general. My current setup looks sth like this:

Client/Server Schema

This is NOT using a library like socket.io or so. (Protocol example below)

So in general, this is what i want to achieve. I have already written an Object which will return a Promise on requests. Since i need the login step in the beginning I wanted to create the object somewhere, and on creating, log in automatically.

Now my questions:

  • Where to define the Class in the ember framework?
  • Where to create/store the object after creation (needs to be singleton since the login is only valid while the socket is open)?
  • How to access the Object, when i need to send requests.

Sample Login request:

Request:

{
    "type": "request",
    "subtype": "apilogin",
    "id": 1234,
    "data": {
        "username": "<string|null>",
        "password": "<string|null>",
        "token": "<string|null>"
    }
}

Answer:

{
    "type": "answer",
    "subtype": "apilogin",
    "id": 1234,
    "error": 0,
    "errormessage": "",
    "data": {
        "token": "<string>"
    }
}

The token is just another way to login which is valid up to 15 minutes after the socket closes. (To reconnect after network errors or similar).

Since i have never really done something like this I'm kinda having problems as where to put stuff in the framework and how to access them.




didInsertElement for only single element EmberJs

I want to call didInsertElement on just one element but not on others, I have a component template with multiple elements, but I just want to use it on specific element.

Any Idea how to do this? Is it possible, if yes, good practice or not..and component having multiple elements pointing towards other components, is that okay?




Stopping scroll when dragging on touch devices

I have the following drag-and-drop list component which works exactly as it should with mouse based events and should work that way with touch events but unfortunately while the touch events are starting to drag the list item the screen scrolls at the same time (making the drag pretty ineffectual).

What i'd like to know is what is the most effect ways to prevent this scroll event from taking place. This code was written using the Ember framework but a JS-specific answer is fine.




GoogleMap + Div container with all the data EmberJs

I am working on a project where we need to bind ember-data with GoogleMap. I have already implemented Map using component, and Map markers gets updated if something gets changed in Data.

Now, I am looking for something which binds my Div (on the right side with all the data in listing) with Map. If I hover over any row it pops up the InfoBox on Map, if I filter the Data on right side it gets updated on Map instantly.

My Right side div is composition of components of different models. Filters are already applied, there are few issue with sorting though but that is something that can be dealt with later.

Ember: 1.8.1 Ember Data : 1.0.0-beta.14.1




jeudi 27 août 2015

Ember: What exactly the chain of modelFor and get do at Route?

I am in Route. What exactly the chain of modelFor and get do the job ?

Syntax:

 import Ember from "ember";

var PagesRoute = Ember.Route.extend({
    model: function(){
        return this.modelFor('campaign').get('pages'); # what exactly it is doing here ?
    }
});
export default PagesRoute;

BTW, what is the best way to debug step by step code?




Cache Data for front end

I am using emberJS and nodeJS for my application development. I have done completely differentiated front end and backend logic separately. Now in my case i want to implement a cache logic for my front end application. when ever i hits an api call to api/xxx, api/vehicve, api/users it will hit nodejs routes and fetch the data as response in front end.

I want to make all the server data in cache as front end and mean while , if server is down i can edit show case this data in my portal and can do edit and update on the cache data.

Is there any plugin or library to achieve caching in front and can edit and update? Please guide an appropriate approach,




Canonical way to represent and query many to one relationships in Solr

I have PostgreSQL and Solr running in the backend, and am using EmberJS with ember-data on the frontend.

In PostgreSQL I have a many to one relation where one article can have many video links. Ember-data requires that this be returned in the format:

{
    articles: {
        //Some number of articles
    },
    videos: {
        //Videos that belong to those articles
    }
}

Now what I intend to do is import from the database into Solr to allow searching on the data. This is where I begin to be confused.

I decided that the best way to go about doing this would be to separately make a core for the videos and make a core for the articles, and then import into both cores separately as well. However, I'm new to Solr and am unsure if having multiple cores is the canonical way to handle a many to one relationship.

Moreover, as far as I know, you can't do a join on two cores when querying which means to construct the JSON that ember requires it'll take multiple queries, which seems wrong to me.

How can I properly represent a many to one relationship in Solr?




Looping Through Ember-Data Model Attrs in a Template

I'm trying to figure out how to dynamically loop through the attributes of an Ember-Data Model I've passed into a Component. Here's what I have:

Templates:

{{!person.hbs}}
{{each-in person as |property value|}}
  <tr>
    <th>
      <td>{{property}}</td>
      <td>{{value}}</td>
    </th>
  </tr>
{{/each-in}}

{{!index.hbs}}
{{person-component person=model}}

Model:

import DS from 'ember-data';

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

Route:

import Ember from 'ember';

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

Is there a simple way to do this from within handlebars? I was thinking possibly that a computed value on the controller might have to do it.




Ember handlebars layout block

Hohoy, is their a way to use a "block" helper in handlebars with Ember? Something like the one in assemble.

The idea is to have a parent template (let's say it's /home):

 <div>
   {{#block "nav-sidebar"}}
     {{> nav-sidebar }}
   {{/block}}
 </div>

And a child template (/home/anything) with:

{{#content "nav-sidebar" mode="prepend"}}
  <p>Hello</p>
{{/content}}

Is it possible? Or is their a more "ember" way to do this? (i.e: replacing a part of a "parent" template from a "child" template). Thanks for your help!




How do I update ember.js to version 2.0.1

I'm fairly new to ember.js

Before starting my project I wanted to upgrade my version to the latest 2.0.1 release.

I went through the steps in the guide.

sudo npm uninstall -g ember-cli
sudo npm cache clean
bower cache clean
sudo npm install -g ember-cli

typing: ember -v gives 1.13.8 just as it did before the 'update'

I can see that the ember-cli website says 1.13.8 is the latest version of ember-cli.
However since the emberjs.com site says the latest release is 2.0.1 and on the homepage the isntruction is to run npm install -g ember-cli I would expect the command
ember -v to return 2.0.1 if I was using the latest release.

I created a new ember project using ember new test and ran
grep -r 'version' * to see if there were any clues but found nothing of interest.
Looking at package.json reveals that ember-data 1.13.8 is one of the dependencies which is also not the latest version (2.0.0)

  • What (if any) is the difference between ember-cli and ember.js versions?
  • When I type ember -v the version of which program is being displayed?
  • If I'm not on the latest release, how can I get it installed?

I'm running ubuntu 14.04




How to filter in a component?

I want to filter one of the objects being passed into my component, however, the lack of answers when I Google this suggests I am going about solving this particular problem the wrong way, but it's hard to Google for what you're doing wrong :P

My data model looks like this:

App.Browser = DS.Model.extend({
    slug: attr('string'),
    versions: DS.hasMany('version', {async: true})
});

App.Version = DS.Model.extend({
    browser: DS.belongsTo('browser'),
    version: attr('string'),
    status: attr('string')
});

I want to create a component (versions-list) that, when passed a browser's versions will separate the versions into different groups based on their status.

<h1>Beta Versions</h1>
     Version 43.0<br>
     Version 42.0
<h1>Current Version</h1>
     Version 41.0
<h1>Retired Versions</h1>
     Version 40.0
     Version 39.0

What's the best way to go about doing this?




Ember save() throws JSON.parse error: "unexpected end of data at line 1 column 1 of the JSON data"

I have a model record created and being saved through a route and controller. When I save the record through the controller (via a savePlace action), I am seeing this error in the JS console:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

I've tried not setting anything on the model as well as setting dummy data on the model, but I get the same error. I am also user ember-cli http-mocks as a test backend to handle JSON responses. I realize it may be the response, but I'm not sure how else to configure the response.

Here's the relevant code:

routes/places/new.js:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.createRecord('place');
  },
});

controllers/places/new.js:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    saveGeom(geom) {
      this.get('model').set('geometry', geom);
    },
    savePlace(data) {
      this.get('model').set('name', this.get('name')).set('description', this.get('description'));
      this.get('model').save().then(function() {
          alert("SUCCESS");
        }, function(error) {
          console.log(error);
        });
    }
  }
});

server/mocks/place.js:

  placeRouter.post('/places', function(req, res) {
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.send({
      "places": {
            id: 1,
            name: "Triangle",
            description: "Ryan Christiani",
            geometry: {
              "type": "Polygon",
              "coordinates": [
                [
                  [-84.32281494140625,34.9895035675793],
                  [-81.73690795898438,36.41354670392876],
                  [-83.616943359375,  34.99850370014629],
                  [-84.05639648437499,34.985003130171066],
                  [-84.22119140625,   34.985003130171066],
                  [-84.32281494140625,34.9895035675793]
                ]
              ]
            }
        }
    });
  });

Thanks!




Listing multiple items using EmberJS 2.0

I have a basic app having using the Fixture Data Adapter and have a model with some basic seed data.

I am having an issue getting the new emberjs 2.0 to list multiple items in a model. The objects are loaded and showing in them ember inspector but are not looping through and displaying in the browser. I have been able to list one at a time but when i switch to adding multiple items it is blank. Any help would be great. Below is a link to the github repository.

http://ift.tt/1hI6HEs

Thanks!




Correct way to destroy a slider instance in willDestroyElement callback

Within an Ember component I am instantiating a slider ( http://ift.tt/1lwYnrc ) and trying to clean it up when then component is destroyed. My setup and tear down functions are:

didInsertElement: function() {
  let component = this;
  let elem = component.$().find('.slider')[0];

  let slider = Ember.$(elem).slider({
    ticks: [0, 20, 40, 60, 80, 100],
    ticks_labels: ['0','20','40','60','80','100'],
    ticks_snap_bounds: 5,
    range: true
  });
  let min = parseInt(component.get('min')),
      max = parseInt(component.get('max'));

  slider.slider('setValue', [ min, max ], true, false);

  slider.on('change', function(evt) {
    component.set('last', evt.value.newValue);
    Ember.run.debounce(component, component.sendScores, 200);
  });

  component.set('slider', slider);
},

willDestroyElement: function() {
  console.log(this);
  console.log(this.get('slider'));
  this.get('slider').destroy();
}

The problem is that I'm getting a Uncaught TypeError: this.get(...).destroy is not a function exception tear down.

The specific question: what am I doing wrong here so the destroy() method is unavailable.

The general question is: should I be storing a "handle" to my slider instance as an Ember property and retrieving it like this or is there a better way?




Ember Brocfile does not import JS and CSS files

I have an Ember CLI application. I am trying to add the BeatPicker jQuery datepickers to my application using app.import() in the Brocfile but they don't seem to be getting included in vendor.js and vendor.css. I installed BeatPicker through Bower and see that the files are in bower_components folder. I am also using retina.js and that seems to get compiled into vendor.js. I am not sure why BeatPicker is not getting compiled. Here is a copy of my Brocfile:

/* jshint node: true */
/* global require, module */

var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

var app = new EmberAddon({
  babel: {
    includePolyfill: true
  }
});

// Retina.js
app.import('bower_components/retinajs/dist/retina.min.js');

// BeatPicker
app.import('bower_components/BeatPicker/build-0.1.3/css/BeatPicker.min.css');
app.import('bower_components/BeatPicker/build-0.1.3/js/BeatPicker.min.js');

module.exports = app.toTree();

Even the paths are correct. What am I missing?




Ember.js correct syntax for consecutive computed properties

I have the following code in my controller. It first filters a set of results based on a search property, and then orders the results.

results: function() {

    var searchTerm = this.get('searchTerm'),
        results = this.get('content');

    if (searchTerm) {
      results = results.filter(function(item) {
        return item.get('name').toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
      });
    }

  }.property('content', 'searchTerm', ),

sortedResults: Ember.computed.sort('results', 'sortProperties'),
    
sortProperties: function() {
    var order = this.get('ordering');
    if (order === 0) {
      return ['name:asc'];
    } else if (order === 1) {
      return ['name:desc'];
    }
  }.property('ordering'),

The template loops over sortedResults:

{{#each sortedResults as |job|}}
    {{job-table-row model=job}} 
{{/each}}

The above works fine. I would like to finally subject sortedResults to a slice function to show a limited number of results. I have tried the following:

slicedResults: function() {
    var sortedResults    = this.get('sortedResults');
    return sortedResults.slice(0,10);
}.property('sortedResults'),

Then looping over slicedResults:

{{#each slicedResults as |job|}}
    {{job-table-row model=job}} 
{{/each}}

In this case, no results are returned. What would be the correct way to use the sorted results in a slice function and then output the result to the template?




What Speciality does nodejs, angularjs, knockout and Ember offer?

I am a Asp.net MVC developer. Recently i started to learn Angularjs for web development and using Web Api as a backend but the question i have is that what would i have learning all these javascript frameworks. What i know is that all these work as a client side framework for web development.

Would not it be sufficient if i learn one of these, or do they offer any speciality in the their field or fulfill a particular need.

Please explain your answer

Thank you in advance




Accessing View function from internal functions in Ember

One of the views in my ember app has the following structure

export default Ember.View.extend({
    didInsertElement: function() {
        window.onload = function() {
            chrome.gcm.onMessage.addListener(function(message) {
                receiveGCM(message);
            });
        }
    },
    receiveGCM: function(message){
        console.log(message);
        //type check here
        //Then call necessary data insertion module
        //Or call the notification module
    }
});

This is throwing an error Error in event handler for gcm.onMessage: ReferenceError: receiveGCM is not defined

Calling receiveGCM(message) with the this object doesn't solve the problem. Wrong this object gets referred. I tried using bind(this). But that doesn't help.

How do I call receiveGCM() from the chrome listener method?




mercredi 26 août 2015

Selection in first drop down populates data in second dropdown but only on first click, why?

i have created 2 drop downs where selection of first drop down effects the data content of the second drop down, I have achieved this much successfully.howsoever,this functionality is occurring inly on first click instead it should happen every time, probably I am missing out on some minor property. Any help is greatly appreciated. here is a link to jsfiddle :to my working code

and here is a link to jsbin,(i dont know what error it is showing in this even when code is exactly same) :to my code

App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.ArticleAdapter= DS.FixtureAdapter.extend({});
App.Article =DS.Model.extend({
        title: DS.attr(),
        body: DS.attr(),
        shouldReloadAll:true,
        comments: DS.hasMany('comment', {async : true})
        //async tells compiler to load data from comment everytime this is rendered
});

App.Comment =DS.Model.extend({
        text: DS.attr(),
        shouldReloadAll:true,
        article: DS.belongsTo('article', { async: true })
});


App.Article.FIXTURES=[ 
                  {
                        id:1,
                        title : 'Ember',
                        body:'Its a great technology but need lot of studying and practice',
                        comments:[1]
                  },{
                        id:2,
                        title : 'Angular',
                        body:'it takes  less understanding but has more coding the ember',
                        comments:[2,3]
                  //this will be an aray coz it is has many relation
                  }
];

App.Comment.FIXTURES=[ 
                      {
                        id:1,
                        text : 'Yyyieee excited to learn ember',
                        aricle: 1
                        //its not an array coz it will be related to single object
                    },{
                        id:2,
                        text : 'I will start Angular once i have fininshed with ember',
                        article: 2
                      },{
                        id:3,
                        text : 'Angular can be interesting',
                        article: 2
                       }
    ];


App.CommentAdapter= DS.FixtureAdapter.extend();


App.IndexController = Ember.ArrayController.extend({
        
        articleValue: null,
        selected: null,
        
        articleStore: Em.computed(function(){
                console.log("data is : " + this.get('articleValue'));
                console.log("data is : " + this.get('selected'));
                 return this.store.findAll("article");
        }).property("selected"),
        
        
        
          availableComment: Em.computed(function () {
        var make = this.get('selected');
        // the line below returns the id and not an object
        console.log(make);
        if (make === undefined || make === null)
            return [];
        return this.get('selected').get('comments');
    }).property('articleValue'),
        
        
        actions:{
                callIndexController: function(){
                        var select= this.get("selected");
                        console.log("hi :" + select);
                }
        }
});

App.IndexRoute = Ember.Route.extend({
          model: function() {
                 return [];
          },
          
        
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ember Starter Kit</title>
</head>
<body>
<script type="text/x-handlebars"> 
    <h2>Welcome to Ember.js</h2>
        {{outlet}}
</script>
  

  
<script type="text/x-handlebars" id="index">
First drop down: 
   {{  
         view "select"
         contentBinding=articleStore
         optionLabelPath="content.title"
         optionValuePath="content.id"
                 prompt="Pick a person:"
                 shouldReloadAll=true
                 selectionBinding=selected
                 valueBinding=articleValue
    }}
<br>
<br>
Second drop down:                
    {{
         view "select"
         contentBinding=availableComment
         optionLabelPath="content.text"
         optionValuePath="content.id"
         prompt="related task:"
                 shouldReloadAll=true
                 valueBinding=articleValue
    }}
</script>

  <script src="http://ift.tt/1rfghyb"></script>
  <script src="http://ift.tt/1U7HzIj"></script>
  <script src="http://ift.tt/1EY7wOg"></script>
  <script src="http://ift.tt/1U7HzIl"></script>
  <script src="js/amit_dropdown.js"></script>
  <!-- to activate the test runner, add the "?test" query string parameter -->
  <script src="tests/runner.js"></script>
</body>
</html>



Error returning promise from Ember Data

I am working on my first Ember app and got it to display as I wanted with the route returning a static JSON object for the model. Now I am trying to refactor to use Ember Data + Mirage and having an awful time.

Good news is that if in the route's model function I try this:

console.log(this.store.find('element', 1));

I see in the console that the request was successful, and the correct object is displayed. (Though note that the Ember inspector, under Data, shows me the object with id = 1 but the key is undefined rather than having the correct value I see in the console.)

The bad news is that if in the model() function I try:

return this.store.find('element', 1);

the app doesn't render at all and I get:

22:46:40.883 "Error while processing route: index" "Assertion Failed: normalizeResponse must return a valid JSON API document:
    * One or more of the following keys must be present: "data", "errors", "meta"." "EmberError@http://localhost:4200/assets/vendor.js:25582:15
_emberMetalCore.default.assert@http://localhost:4200/assets/vendor.js:15745:13
ember$data$lib$system$store$serializer$response$$normalizeResponseHelper@http://localhost:4200/assets/vendor.js:123912:1
ember$data$lib$system$store$finders$$_find/</<@http://localhost:4200/assets/vendor.js:124107:25
Backburner.prototype.run@http://localhost:4200/assets/vendor.js:10838:18
ember$data$lib$system$store$$Store<._adapterRun@http://localhost:4200/assets/vendor.js:129461:16
ember$data$lib$system$store$finders$$_find/<@http://localhost:4200/assets/vendor.js:124106:1
tryCatch@http://localhost:4200/assets/vendor.js:60829:14
invokeCallback@http://localhost:4200/assets/vendor.js:60844:15
publish@http://localhost:4200/assets/vendor.js:60812:9
@http://localhost:4200/assets/vendor.js:40152:7
Queue.prototype.invoke@http://localhost:4200/assets/vendor.js:11532:9
Queue.prototype.flush@http://localhost:4200/assets/vendor.js:11596:11
DeferredActionQueues.prototype.flush@http://localhost:4200/assets/vendor.js:11392:11
Backburner.prototype.end@http://localhost:4200/assets/vendor.js:10720:9
Backburner.prototype.run@http://localhost:4200/assets/vendor.js:10842:13
run@http://localhost:4200/assets/vendor.js:29656:12
ember$data$lib$adapters$rest$adapter$$RESTAdapter<.ajax/</hash.success@http://localhost:4200/assets/vendor.js:122361:15
jQuery.Callbacks/fire@http://localhost:4200/assets/vendor.js:3350:10
jQuery.Callbacks/self.fireWith@http://localhost:4200/assets/vendor.js:3462:7
done@http://localhost:4200/assets/vendor.js:9516:5
.send/callback@http://localhost:4200/assets/vendor.js:9920:8
_readyStateChange@http://localhost:4200/assets/vendor.js:64353:9
_setResponseBody@http://localhost:4200/assets/vendor.js:64419:9
respond@http://localhost:4200/assets/vendor.js:64440:7
handleRequest/<@http://localhost:4200/assets/vendor.js:65413:11
resolve@http://localhost:4200/assets/vendor.js:65450:9
handleResponse/<@http://localhost:4200/assets/vendor.js:65441:11
"1 vendor.js:38337:5
logError() vendor.js:38337
defaultActionHandlers.error() vendor.js:38280
triggerEvent() vendor.js:38391
trigger() vendor.js:60414
Transition.prototype.trigger() vendor.js:60228
Transition/this.promise<() vendor.js:60048
tryCatch() vendor.js:60829
invokeCallback() vendor.js:60844
publish() vendor.js:60812
publishRejection() vendor.js:60747
<anonymous> vendor.js:40152
Queue.prototype.invoke() vendor.js:11532
Queue.prototype.flush() vendor.js:11596
DeferredActionQueues.prototype.flush() vendor.js:11392
Backburner.prototype.end() vendor.js:10720
Backburner.prototype.run() vendor.js:10842
run() vendor.js:29656
ember$data$lib$adapters$rest$adapter$$RESTAdapter<.ajax/</hash.success() vendor.js:122361
jQuery.Callbacks/fire() vendor.js:3350
jQuery.Callbacks/self.fireWith() vendor.js:3462
done() vendor.js:9516
.send/callback() vendor.js:9920
_readyStateChange() vendor.js:64353
_setResponseBody() vendor.js:64419
respond() vendor.js:64440
handleRequest/<() vendor.js:65413
resolve() vendor.js:65450
handleResponse/<() vendor.js:65441




Harnessing "computed properties aren't computed unless something tries to get them"

I'm learning Ember via ember-cli. I have a problem which I believe is related to "computed properties aren't computed unless something tries to get them", but I can't figure out how to "get" the property in this case. I created an app, one controller, one service, and one template using ember-cli:

ember new st
cd st/
ember g controller index
ember g service start
ember g template index

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  start: Ember.inject.service(),
  value: Ember.computed('start', function () { 
    return this.get('start').value;
  }),
  actions: {
    update: function() {
      this.get('start').update();
      alert(this.get('start').value);
  }
 }
});

Service:

import Ember from 'ember';

export default Ember.Service.extend({
  value: "original",
  update: function() {
    this.set('value', "updated");
  }
});

Template:

<p>{{value}}</p>
<br>
<button {{action "update"}}>Update</button><br>

Then I serve this with "ember serve". As expected the value shown is the initial value "original". When I click the Update button, I get an alert showing the new value "updated" however the original value stays on the screen. How can I "get" this injected property such that it is computed and therefore updated?

ember-cli is 1.13.8, ember itself is 2.0.1




Can ember-mocha tests run in parallel?

Our tests are getting too large and require almost a minute wait for the tests to finish running in the browser. I noticed there are existing plugins for parallel mocha but how can I incorporate it within testem and ember-mocha?

See: http://ift.tt/1KlGOoS




Update Ember model from controller

currently i try to create like infinite scroll by putting some button in the template to load more data.

bellow is the code

index.hbs

 {{#each model}}
  <p>{{name}}</p>
 {{/each}}
  <button {{action "addMore"}}>add MORe </button>

controller/index.js

 import Ember from 'ember';

  export default Ember.ArrayController.extend({
  actions:{
  addMore: function (){
  this.get("model").push({name:"some data"});

  }
  }

  });

and route index.js

 import Ember from 'ember';

 export default Ember.Route.extend({
 model: function() {
 var v=[];
 return v

 }
 });

The problem was, after user clicked the button, the controller pushed the data into the model, but the template did not show model with current data (data after the controller push new data into the model).

please help

thanks




ASP.NET Web API - Configure the JSON response to conform to JSON API

Version 1 of my ASP.NET Web API for Ember.js was producing JSON that looked like this:

     [{"id":1,"name":"House of Crap","category":"Retail","street_name":"Washington Street"},
     {"id":2,"name":"Sketchy Automotive","category":"Automotive","street_name":"4th Street"},
     {"id":3,"name":"Toxins Are Us","category":"Chemical","street_name":"Highway 93"},
     {"id":4,"name":"Tricky Restaurant","category":"Restaurant","street_name":"4th Street"}]

I need something that looks like this:

     {"property":
     [{"id":1,"name":"House of Crap","category":"Retail","street_name":"Washington Street"},
     {"id":2,"name":"Sketchy Automotive","category":"Automotive","street_name":"4th Street"},
     {"id":3,"name":"Toxins Are Us","category":"Chemical","street_name":"Highway 93"},
     {"id":4,"name":"Tricky Restaurant","category":"Restaurant","street_name":"4th Street"}]}

One of my subs accomplished this as follows: He created a simple view-model class.

    namespace EnvironWeb.ViewModels
    {
        public class PropertyVM
        {
            public IEnumerable<property> property { get; set; }
        }
    }

He then made the GetProperties controller method of the type of the new class.

    public PropertyVM GetProperties()
    {
        var model = new PropertyVM();
        model.property = repository.GetAll();

        return model;
    }

It's clever, but is it the best approach? The JsonConverter looks promising, but I'm not sure I can accomplish it with the JsonConverter.




Ember form validation

I'm kind of new to Ember and I'm on something that should be quite simple. Just trying to validate a form actually. Using ember-forms and ember-validations.

Here is the part of the structure, I'll be quite exhaustive so you can get to the point but there is really not a lot of code:

 /app
   /controllers
     /admin
       /create-user.js
   /models
     /admin
       /create-user.js
   /routes
     /admin
       /create-user.js
   /templates
     /admin
       /create-user.js

First, I'm not sure it's the good structure, especially about the model.

The model:

import DS from 'ember-data';

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

The controller:

import Ember from 'ember';
import EmberValidations from 'ember-validations';

export default Ember.Controller.extend(EmberValidations, {
  validations: {
    entity: {
      presence: true,
      length: { minimum: 5 }
    }
  },
  actions: {
    createUser() {
      console.log("create");
    }
  }
});

The route:

import Ember from 'ember';

export default Ember.Route.extend({
});

The template:

<h3>Create User</h3>

<div class="row">
  <div class="col-sm-6">
    {{#em-form action="createUser" model=create-user}}
      {{em-input
        label="Name / Entity"
        property="entity"
        placeholder="The name of the user or the entity"}}

    {{/em-form}}
  </div>
</div>

I know I'm missing something and I'm pretty sure it has to do with the model (I tried a lot of thing such as model=admin/create-user in the template).

EDIT: there's no error or whatever in the console, the validation is just not called.

Thx for your help!




How to use Ember CLI with old version of Ember.js?

I'm working with an API that conforms to an older version of the JSON API spec. I know the following resources can interact with it successfully because there's another app built with them:

  • Ember 1.7.0
  • Ember Data 1.0.0-beta.9
  • Ember JSON API 1.0-beta.3
  • jQuery 1.11.1

Can I use Ember CLI with these old resources? How would I do that?




Ember communicate between child components

I'm trying to make a header component, which has several inside components, such as a button, and one of them opens a side menu that is a child component also.

How can target an action of one child component to another child component?

In this case, target the open action in the button component to the overlay component?

{{#header-block class="main-nav"}}

  {{button-icon icon="fi-torso" class="nav-action left" openMenu=(action "open" target=) }}

  {{#overlay-block}}
    {{#side-menu}}
      <p>side menu one</p>
    {{/side-menu}}
  {{/overlay-block}}

{{/header-block}}




Where and how to include Ember model functions

I am working on a simple Ember app that shows ID's for list elements. The ID's are computed with simple functions based on the element sequence (and some other simple factors). For example:

<div class="content-id element">[ELEMENT ID]</div>
<div class="content-name">{{element.name}}</div>

I don't want to hardcode the element id's into the JSON object, but rather compute them in a simple function. Would it be best to place this function in the route object or in the component? What's the syntax?

Thank you.




Ember Run Loop in testing mode

I'm using http://ift.tt/1JwkRhO add-on and everything worked nicely until Ember 1.10.1, but since Ember 1.11.0 Ember's run loop start crashing in E2E testing saying that we were trying to access a destroyed object, I have been trying to fix it but I couldn't so I made a PR http://ift.tt/1fGE7kI reproducing the error in tests/dummy and tests/integration but neither they know how to fix it, please help.

We think is something related with Stripe.js (http://ift.tt/KXmU7y) because theu embed an Iframe when the script in loaded in the browser.




How to distinguish self-referential models in Ember

I have a friend model that has a self-reference to relatedFriends:

export default DS.Model.extend({
  friends: hasMany('friend', {inverse : 'relatedFriend'}),
  relatedFriend: belongsTo('friend', {inverse : 'friends'})
});

I'm running into an issue when loading a set of friends, and side-loading their related friends.

Say my route's model hook looks like this:

model() {
  return this.store.find(‘/friend’, {page: 1});
}

The server responds with 10 friend records for page 1. But, those friends have friends, and I want to sideload 3 related friends for each primary friend. So, I’ll also have 30 friends sideloaded.

Typically, for this type of response, my json would look something like

{
  friends: [
    {id: 1, ...
    {id: 2, ...
    {id: 2, ...
  ]
}

The problem is, if my response puts all these under a single friends key in my json, model won't be the single page of friends I requested; it will be all the friends (40 in this example).

How can I differentiate between the "primary" friends from my query, and the side-loaded related models?




Ember Data EmbeddedRecordsMixin won't save newly created records

I'm using Ember Data 1.13.7 and Ember 1.13.6 with ActiveModelSerializer and EmbeddedRecordsMixin.

I have 2 models:

// models/post.js
export default DS.Model.extend({
  //bunch of attrs
  commentStuff: DS.belongsTo('commentStuff', {async:true})
}

and

//models/comment-stuff.js
export default DS.Model.extend({
  //bunch of attrs
  post: DS.belongsTo('post', {async: true))
}

in my serializer I have

export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  isNewSerializerAPI: true,

  attrs: {
    commentStuff: {serialize: 'records', deserialize: 'ids'}
  },

  keyForAttribute(attr){
    if(attr === 'commentStuff'){
      return 'comment_stuff_attributes';
    } else {
      return this._super(attr);
    }
  }

});

This works perfectly when I edit existing records and then post.save() but when I create new records with:

var post = this.store.createRecord('post');
post.commentStuff = this.store.createRecord('commentStuff');

And then fill in all their respective attributes. The json sent to the server on post.save() shows none of the commentStuff attributes and just returns null.

{post: {
  attribute1: 'whatever',
  attribute2: 'smth',
  attribute3: 4,
  comment_stuff_attributes: null}
}

Is there a different way I should be saving/creating new records?




jQuery Geocomplete options not tappable in Emberjs Cordova app

I'm using the jQuery Geocomplete plugin as a component in my Emberjs Cordova app as an address picker. It works fine in the browser, but when built in iOS, none suggested PAC items are clickable.

My component template:

<form {{ action "saveAddress" on="submit" }}>
  {{input value=addressInput type=textfield class="address-input" placeholder="Enter an address" action="locateAddress" on="key-press"}}
  {{input type="text" value=formattedAddress name="formatted_address" placeholder="Address" class="formatted-address"}}
  <input type="submit" value="Add Address"/>
</form>

And my component

  actions: {
    saveAddress: function() {
      this.sendAction('saveAddress', {
        formattedAddress: this.$("input.formatted-address").val()
      });
    },
    locateAddress: function () {
      this.$("input.address-input").geocomplete({
        map: "#map",
        details: "form"
      });

    }
  }

I have seen people refer to using the following code as a hack that fixes the problem, but it doesn't seem to work for me:

$(document).on({
  'DOMNodeInserted': function() {
    $('.pac-item, .pac-item span', this).addClass('needsclick');
    }
  }, '.pac-container');

When I press Enter on the iPhone keyboard it picks the first item on the list and enters it. But tapping does nothing. Anyone any ideas?




Serializing model with multiple primary keys

I have a Rails API that communicates with an Ember app. I need to be able to serialize a model that has two primary keys instead of the default id.

This is what it looks like right now:

Models

# This is the problem model:
class Value < ActiveRecord::Base
  self.primary_keys = :foreign_id, :type_id
  belongs_to :type, foreign_key: :type_id
end

class Type < ActiveRecord::Base
  has_many :codes, foreign_key: :code_type_id
  has_many :values, foreign_key: :type_id
end

class Code < ActiveRecord::Base
  belongs_to :type, foreign_key: :code_type_id
end

class Activity < ActiveRecord::Base
  has_many :values, -> (object){ where("type_subject_area = ?", "Activity") }, foreign_key: :foreign_id
end

Schema

create_table "values", id: false, force: :cascade do |t|
  t.integer  "foreign_id"
  t.string   "type_subject_area"
  t.integer  "code_id"
  t.integer  "type_id"
  t.string   "type_title"
  t.text     "text"
  t.datetime "created_at"
  t.datetime "updated_at"
end

add_index "values", ["foreign_id", "type_id"], name: "index_values_on_foreign_id_and_type_id", unique: true, using: :btree

create_table "types", force: :cascade do |t|
  t.integer  "id"
  t.string   "title"
  t.string   "subject_area"
  t.datetime "created_at"
  t.datetime "updated_at"
end

add_index "types", ["id"], name: "index_types_on_id", unique: true, using: :btree

create_table "activities", force: :cascade do |t|
  t.integer  "id"
  t.datetime "created_at"
  t.string   "name"
end

add_index "activities", ["activity_type"], name: "index_activities_on_activity_type", using: :btree
add_index "activities", ["id"], name: "index_activities_on_id", unique: true, using: :btree

create_table "codes", force: :cascade do |t|
  t.integer  "id"
  t.string   "description"
  t.string   "code_value"
  t.integer  "code_type_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

add_index "codes", ["id"], name: "index_codes_on_id", unique: true, using: :btree

Serializers

class ActivitySerializer < ActiveModel::Serializer
  attributes  :id, :name
  has_many :values
end

class UDFValuesSerializer < ActiveModel::Serializer
  attributes :foreign_id, :type_subject_area, :type_id, :text, :type_title
end

As you can see, a type has many values and codes. An activity has many values, though it's only related to the values that have a subject area of "Activity". Since values don't have an individual primary key, I'm not sure how to format it in such a way that works in Ember. From what I understand, Ember needs to have an id available in order to receive the values.

Thoughts? Ideas? I'm afraid this needs to be in this format because the Rails API is communicating and syncing with another, larger API.




In Ember, should I put my theme layout in application.hbs or index.html?

I started working on Ember js using ember-cli and I want to migrate an existing code written in html, jquery and css. I am not sure if its best to put it in the index.html or application.hbs ?




ember tests passing in chrome, not in phantomjs

I have tests for an addon which pass in chrome, but fail in phantomjs.

It seems to be a problem similar to this question. However, I tried the solution there and it didn't work for me.

The code is all available in the public repo linked above. The failures are exhibited in the failing travis build on github. Any ideas on how to diagnose better and fix?

EDIT -- actual error message


        Died on test #1     at http://localhost:7357/assets/test-support.js:3062
            at test (http://localhost:7357/assets/test-support.js:1945)
            at test (http://localhost:7357/assets/dummy.js:2090)
            at http://localhost:7357/assets/dummy.js:2885
            at http://localhost:7357/assets/vendor.js:150
            at tryFinally (http://localhost:7357/assets/vendor.js:30)
            at http://localhost:7357/assets/vendor.js:156
            at http://localhost:7357/assets/test-loader.js:29
            at http://localhost:7357/assets/test-loader.js:21
            at http://localhost:7357/assets/test-loader.js:40
            at http://localhost:7357/assets/test-support.js:6775: Can't find variable: Symbol




Ember - Set a Dynamic Page Title per route

I have set up my Ember app to use the pod structure. I've created a topbar-nav component which I display on the main page. In the topbar-nav component I have set up the page title, which I would like to set automatically per route so for the dashboard route the title should be Dashboard, for the dashboard/categories the title should be categories and so on.

Here's my app structure:

  • app
    • application
    • components
      • topbar-nav
    • dashboard
    • categories

The app router - router.js

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

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

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

export default Router;

And the templates:

application/template.hbs

<aside>
    {{sidebar-nav}}
</aside>

<main>
    <header>
        {{topbar-nav}}
    </header>

    {{outlet}}
</main>

components/topbar-nav/template.hbs

<nav class="topbar-nav">
    <div class="text-center">
        <h5 class="page-title">{{title}}</h5>
    </div>
</nav>

{{yield}}

components/topbar-nav/component.js

import Ember from 'ember';

export default Ember.Component.extend({
    title: 'Component title'
});

As you can tell already the title I get rendered is 'Component title'

The most accurate answer I got by now is this one:

Ember dynamic titles

though after trying a lot of different approaches I couldn't find a good solution.

Is there a clean and easy way of doing this? Any ideas and solutions are much appreciated.




Ember-cli creating more than 30000 files

I'm new to ember and after following a few guides, I've been playing around with ember apps. I'm using ember-cli to create an app, so I use

$ ember new 'app-name'

which creates the app as expected with the 'app' and 'dist' folder. But it also creates a lot of other files. I only discovered this while deleting the folder when the windows delete dialog box showed deleting more than 30000 files.

Is it that I'm doing something wrong that's causing unnecessary files to be created? Is there a way to avoid this?




jQuery unbind/off event

I'm trying to prevent a memory leak caused by part of the code which doesn't get fired when the element is destroyed.

My code attaches an event to the document on mouseup and does stuff with a particular element of the DOM. If the element is removed, the event should be disabled by willDestroyElement of Ember but some times it doesn't happens so I need to disable it manually.

To do so I put on the very begin of my event function this string:

onMouseUp: function(evt) {
    // relevant part of the code:
    if (!this.$()) {
      return $(document).off(evt);
    }

    [...]

In this way looks like the event is correctly unbinded from the document.

I can't find documentation about this use case and I'd like to know if doing so could lead to side effects or anything bad?




Latest version of ember-cli compatible with ember 2.0

I am following the ember 2.0 guides at : http://ift.tt/1MU3WN9

I noticed it installs ember 1.13.0 even tough I am in the 2.0 section. What is going on? Should I copy new 2.0 version in the generated ember-cli folders?

How do you setup ember-cli with ember 2.0?




How do I pluck user ids from all comments of an article?

I have an article that hasMany comments. A comment belongsTo a user and an article. So basically a comment has an article and user foreign key id.

I am trying to "pluck" / place all of the comment user ids, of the article, into an array.

I have a computed property that does:

userIds: Ember.computed('article.comments.length', {
  get() {
    return this.get(‘article.comments’).mapBy(‘user.id’);
  }
})

Returns: [undefined].

Expected result: [1,2,3,4]. Assuming 1,2,3,4 are user ids.




Is it possible to tweak Ember blueprints

When writing acceptance tests for our application, we use ember generate to stub out the test (ember generate acceptance-test <name>).

The next step is typically to modify the generated test to call ember-simple-auth-testing's authenticateSession() in the module block (and most likely perform some setup with ember-data-factory-guy).

What I would like to do is make a slight tweak to the acceptance-test blueprint's template, however I can't seem to find any documentation on how to extend blueprints.

Does anyone know if any such documentation exists, or how I might go about doing this?

Thanks!




Ember: all nested roots params and query params

I am actually trying to implement a 'back' functionnality on my project. The usecase is that there should be a 'back' button on some pages to get back. And it should be a little bit different from the 'back' browser button default behaviour. Here it is: a user is on a search page (let's call this page backable route) and she clicks on an item to see the item details page (let's call it backing route). Then she may do some actions on this page by modifying the query parameters of this backing route. And if she wants to get back to the search page (backable route), she clicks the 'back' button (not on browser). Actually this what I do:

  1. user is on the search page
  2. she clicks on an item
  3. within the action that do the transition to the backing route I get the current route (which is the backing route) name and its parameters and store it
  4. then the user does something on the item details page and clicks on the 'back' button
  5. within the 'back' action I get the backing route name and its parameters and do the transition to it

The problem with this approach is the nested routes. If a backing route has nested routes then the nested routes' params (model id and query parameters) are lost.




How to render component/helper from another one?

I have render-component ( source ) which used to render components/helpers from controller fields. It worked fine for ember 1.9.1 but after updating up to ember 1.12.1 I found changes in API. After updating code I restore simple cases ( like render view by name from some property ). But largest part of functionality still broken.

I'm interesting about where can I read more about such things like

  • env ( which used inside components/helpers internal implementation )

  • morph ( I understand that it's a part of html-bars, but I'm interested in more documentation )

  • hooks ?

Can anyone share some experience at creating such helper ? Or way to find solution in such cases? ( I mean that this things not fully documented )

Thx in advance




mardi 25 août 2015

Using Ember component's methods inside template

I've just started learning Ember and one thing I'm confused that if I can access component's method inside the template.

For example, I have a note-list component that render list of note-line as follow:

<ul class="list">
  {{#each notes as |note|}}
    {{note-line note=note index=@index selected=(isSelected note)}}
  {{/each}}
</ul>

The note-list component is defined as:

Ember.Component.extend({
    tagName: '',
    isSelected(note) {
        return note.id === this.get('selectedNote').id
    }
})

But I'm getting error Assertion Failed: A helper named 'isSelected' could not be found.

I think I could solve it with helpers, but it seems to be not a good solution to create a separate helper for a behaviour of a specific component.

Please help to advise me some better way to deal with it.

Thanks very much.




Accessing Model Data in Template

I have a route defined like so:

Router.map(function() {
    this.route('games', function() {
        this.route('game', {path: '/:game_id'}, function() {});
    });
});

When I visit path /games/1 I have to access the model data like so:

{{model.title}}

Reading the documentation, it seems that the controller would make the model data available without the model prefix so I thought I'd be able to do this:

{{title}}

But it doesn't work without model. I'm not creating the controller because I don't need to extend it for this particular route/template. Is accessing the model data via the model prefix accurate? Or am I possibly doing something else wrong?




Getting `this` to work in link-to helper of component

I have a component defined like so:

<div class="col-sm-4 col-md-2">
  <div class="thumbnail">
    <img src="assets/images/{{image}}">
    <div class="caption">
      <h5>{{#link-to 'games.game' this}}{{title}}{{/link-to}}</h5>
    </div>
  </div>
</div>

And I am using it like so:

{{#each model as |game|}}
  {{game-details-small title=game.title image=game.image id=game.id}}
{{/each}}

I kind of accidentally got the link-to helper to work by passing in id=game.id as a property. However, if I remove that the link loses the reference to the id. I'm trying to find documentation on how passing in the id makes this reference the id correctly, but I can't find it. Any suggestions, links, or explanation would be helpful.




Proper Use of Nested Routes

I was trying to get the following working:

Router.map(function() {
    this.route('games', function() {
        this.route('game', {path: '/:game_id'}, function() {});
    });
});

I had a directory structure like so:

templates
  - games
    - index.hbs
    - game.hbs

Clearly, this wasn't working. I couldn't really figure out how to get game.hbs to render. After doing some research, I stumbled on an article from 2013 and that led me to this solution:

Router.map(function() {
    this.route('games', function() {});
    this.route('game', {path: 'games/:game_id'}, function() {});
});

templates
  - games
    - index.hbs
  - game
    - index.hbs

Note that I had to include the empty function() { } in both routes to get the subdirectory structure to work.

I'm using Ember 1.13.7 and I'm wondering if this is still the correct approach. Or is there a way I can nest the game route without having anything additional on the path to get it to work?




Ember data and promises in model

I'm currently trying to load an array of promises to the model, but when I start looping through results in the template, I can't access any relationships. Even though if I just return a single promise, I can access the relationships within the template.

I'm I missing something on how to handle the return values from the promises to be handle as if it was single?

Model - grouped item

export default DS.Model.extend({
  group:          DS.belongsTo('group', { async :  false }),
});

Model - group

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

Single model example

model : function(){
   return this.store.query('groupedItem', { group_code: 'HOME', position : 1 });
}

In template I can access model relationships like this

{{#each model as |section|}}
  <p>{{section.id}}</p>
  <p>{{section.group.id}}
{{/each}}

------ Model as array promise --------

model : function(){
   return Ember.RSVP.Promise.all(Ember.A([
      this.store.query('groupedItem', { group_code: 'HOME', position : 1 }),
      this.store.query('groupedItem', { group_code: 'HOME', position : 2 }),
    ]))
}

In template, accessing relationships fails

{{#each model as |section|}}
  {{#each section.content as |item|}}
     <p>{{item.id}}</p>
     <p>{{item.group.id}}
  {{/each}}
{{/each}}




EmberJS in-repo-addon not compiling CoffeeScript files

We are using in-repo-addons in our projects and I recently came across and issue when trying to switch over to CoffeeScript.

We've install CoffeeScript support through the recommended method ember install ember-cli-coffeescript and that works without an issue. The strangeness starts when trying to use CoffeeScript in the in-repo-addon.

Coffee files added under repo->test-support will compile without issue but anything in any other folder will not. I've tried just about everything under the sun and compared my project with others where coffee works with the repo.

Has anyone run into this type of issue before and if so, what steps should I take to resolve it?




Ember Communication Between Components

I'm developing a webapp to display and search documents using Mozilla's PDFJS project. I've laid out the main wrapper div like this:

<div class="wrapper">
    {{searchComponent searchComponent=searchComponent}}
    {{pdfViewer pdfSearchComponent=searchComponent}}
</div>

This allows me to later add other types of viewers in there, like so:

{{otherViewer otherSearchComponent=searchComponent}}

The outer wrapper is an ember component as well. So it's controller looks like:

Ember.controller.extend({
   searchComponent: null,
   .
   .
   otherProperties,
   actions: { }
});

And the searching component binds itself on itialization, as inspired from this source: http://ift.tt/1PMsQLa

Ember.controller.extend({
    searchComponent: null,
    .
    .
    onStart: function(){
       this.searchComponent = this;
    }.on('init'),
    .
    .
    actions: {
        someAction: function() {
            //do something
        }
    }
}

So I can now reference the component from the main pdfViewer like this:

this.get('searchComponent').send('someAction')

To get the response, right now I bind another property to all the controllers / templates, and then watch for a change on that property in the viewer controller, after which I can place the results where they need to be.

Is there a way to send a 'message' from my 'pdfViewer' to my 'searchComponent' and receive a 'response' without explicitly binding them together, as above?




Ember component property not being set on change listener

Hello I have a radio input component below, Now the issue I'm having is the property "value" is not being updated via the "radios" change function below. I log it and I get the updated value but it isn't being set so that if I can "this.get('value')" it doesn't yield the latest set value. Any help would be appreciated.

export default Ember.Component.extend({

// -------------------------------------------------------------------------
// Dependencies

// -------------------------------------------------------------------------
// Attributes

/** @type {String[]} */
attributeBindings: [
    'disabled'
],

/** @type {String[]} */
classNames: [
    'form-group',
    'sl-radio-group'
],

/** @type {Object} */
layout,

/** @type {String} */
tagName: 'fieldset',

// -------------------------------------------------------------------------
// Actions

// -------------------------------------------------------------------------
// Events

// -------------------------------------------------------------------------
// Properties

/**
 * Whether the radio buttons should be disabled
 *
 * @type {Boolean}
 */
disabled: false,

/**
 * Whether the radio buttons should be put inline together
 *
 * This value is null by default, which means that the sl-radio-group will
 * not override anything. If the `inline` value is false, the children
 * buttons will be forced to not inline, and if true, they will be forced to
 * be inline.
 *
 * @type {?Boolean}
 */
inline: null,

/**
 * The "name" attribute for the children radio buttons
 *
 * Similar to the `inline` property; the default value is null, so the
 * children buttons will not be overridden. Any string value will overwrite
 * the children buttons' name property.
 *
 * @type {?String}
 */
name: null,

/**
 * Whether the radio buttons should be readonly
 *
 * @type {Boolean}
 */
readonly: false,

/**
 * The component's current value property
 *
 * @type {?String}
 */
value: null,

// -------------------------------------------------------------------------
// Observers

/**
 * Initialize the group-wide options and setup child radio buttons
 *
 * @function
 * @throws {ember.assert} Thrown if the `name` property is not set
 * @returns {undefined}
 */
initialize: Ember.on(
    'didInsertElement',
    function() {
        const name = this.get( 'name' );

        const value = this.get( 'value' );
        const isDisabled = this.get( 'disabled' );
        const isInline = this.get( 'inline' );
        const isReadonly = this.get( 'readonly' );

        /**
         * To each sl-radio component apply...
         *
         * - Attributes: name, disabled, readonly
         * - Classes: radio, radio-inline
         */
        this.$( '.sl-radio' ).each( function() {
            const radio = Ember.$( this );
            const input = Ember.$( 'input', this );

            input.attr( 'name', name );

            if ( isDisabled ) {
                input.prop( 'disabled', true );
                radio.addClass( 'disabled' );
            }

            if ( isReadonly ) {
                input.prop( 'readonly', true );
                radio.addClass( 'readonly' );
            }

            if ( true === isInline ) {
                radio.removeClass( 'radio' );
                radio.addClass( 'radio-inline' );
            }

            if ( false === isInline ) {
                radio.removeClass( 'radio-inline' );
                radio.addClass( 'radio' );
            }
        });

        // Pre-select radio button if a value is set
        if ( value ) {
            this.$( `input[name=${name}]:radio[value=${value}]` ).prop(
                'checked', true
            );
        }

        // Apply change() listener to keep group value in sync with select
        // sl-radio option
        const radios = this.$( `input[name=${name}]:radio` );
        radios.change( () => {
            this.set( 'value', radios.filter( ':checked' ).val() );
        });
    }
),

/**
 * Remove events
 *
 * @function
 * @returns {undefined}
 */
unregisterEvents: Ember.on(
    'willClearRender',
    function() {
        this.$( `input[name=${this.get( 'name' )}]:radio` ).off();
    }
)

});