mercredi 31 mai 2017

How to make a new flash type in ember-cli-flash add on?

Using the flash add on as a service. By default it provides 4 types of flashes (success, info, danger and warning). I don't want to mess up the already written flash component. I want to add a new type which would take some parameters and add something extra to the success flash type. How can this be done?




Part time freelance software developer position

Though I am a full time Web UI developer in Ember.js, since last three years, still I want to work part time for few hours in a day or sometimes few hours in a week in Ember.js JavaScript

This might not be the exact forum to ask such questions, excuse me for that.

Plz tell me real solutions to this query of mine.

Thanks in advance

Regards

Dn




How can I avoid "Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number" when refreshing an ember page?

There's this really annoying feature about Ember that I'm not sure how to get around. I may have a url that looks like the following

http://{my-blog-name}/posts/view/{some-blogpost-ID}

The way I get to this page is by clicking on a link inside of my {my-blog-name}/posts page. This works and will display the page as expected. However, if I try to refresh the page, or if I just literally type my http://{my-blog-name}/posts/view/{some-blogpost-ID} into my url search box, I will get

Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number

Here is how I navigate to the posts/view/{some-blog-id} page.

posts.hbs

<li class="title-list-item"></li> 

view.js

import Ember from 'ember';

var siteId;

export default Ember.Route.extend({
    model(params) {
        siteId = params.site_id;
        return this.store.findRecord('post', params.site_id);
    }
});

This is really frustrating because it means I can't make a blog post and share the link with a friend. Why does this happen and is there a good way to get around it?




Ember transitionTo and set controller attribute in callback

I have Ember code to transitionTo some route & I want to set controllerAttr1 on my.route

this.get('router').transitionTo("my.route").then(function (newRoute) {
    newRoute.controller.set("controllerAttr1", controllerAttr1); // This code is called later
});

In my.route, I have a check for controller.controllerAttr1

model: function (params) {

},

setupController: function setupController(controller, model) {
    // Issue us below check is executed before the callback code which sets "controllerAttr1"
    if (controller.controllerAttr1) {
        //Do something
    }
}

However, my issue is this check for controller.controllerAttr1 happens before the callback code is executed

newRoute.controller.set("controllerAttr1", controllerAttr1);

How do I fix this ?




Emberfire: How to access parent models from embedded child models?

According to the emberfire guide, it is advised to define embedded relationships the following way:

// app/models/post.js

import DS from 'ember-data';
export default DS.Model.extend({
  comments: DS.hasMany('comment', { async: false, inverse: null }),
});

That is, set inverse to nullin the options of the relationship.

This makes perfect sense, since this causes the references to the parent model to not be saved in the child model, and we don't need those because of the embedding.

However there is no word about how to define the children. Obviously one would need to define the relationship in the child model somehow (if one wants to access the parent), for example:

// app/models/comment.js

import DS from 'ember-data';
export default DS.Model.extend({
  post: DS.belongsTo('post')
});

But this doesn't work. The parent isn't accessible. I even tried to define the inverse in the child ( { inverse: 'comments' } )

Is there a way to do this, or is this maybe a bug / shortcoming of emberfire at the moment?




Google OAUTH2 no refresh_token received

I am using emberjs and i could get this response from http://ift.tt/1GDfmSD

{
 "access_token": "snip",
 "token_type": "Bearer",
 "expires_in": 3600,
 "id_token": "snip"
}

but i am never getting refresh token not even on first authentication. I am stuck with it for hours can anyone help me

My request params

code:4/6_Rm706y9Y4vAFSiR6BAF6GXEIQgG8IKkk_8JHSC7sU
redirect_uri:http://localhost:8080/app
client_id:****************
client_secret:****************
scope: null
grant_type:authorization_code
access_type:offline
approval_prompt:force




Setup of ember-service-worker-cache-fallback to sync data

I'm a beginner in ember and service workers. My goal is to setup a simple ember app that works offline. I basically have a list of elements that are available through an API (GET/POST).

When I'm online, everything works as expected. I can GET the list and POST new items. When I'm offline the app works, but network requests are not executed once I go back online. All network requests are actually executed while I'm offline (and obviously fail). I would expect that the service worker caches the network requests and executes them only once I'm back online. Is this wrong?

Here some information about my setup:

Ember version:

  • ember-cli: 2.13.1
  • node: 7.10.0
  • os: darwin x64

Service Worker Add-ons (as listed in app/package.json):

"ember-service-worker": "^0.6.6",
"ember-service-worker-asset-cache": "^0.6.1",
"ember-service-worker-cache-fallback": "^0.6.1",
"ember-service-worker-index": "^0.6.1",

I should probably also mention that I use ember-django-adapter in version 1.1.3.

This is my app/ember-cli-build.js

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

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    'esw-cache-fallback': {
      // RegExp patterns specifying which URLs to cache.
      patterns: [
        'http://localhost:8000/api/v1/(.*)',
      ],

      // changing this version number will bust the cache
      version: '1'
    }
  });

  return app.toTree();
};

My network requests (GET/POST) go to http://localhost:8000/api/v1/properties/.

This is my app/adapters/applications.js

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {

  namespace: 'api/v1',
  host: 'http://localhost:8000',
  authorizer: 'authorizer:token',
  headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  buildURL: function(type, id, record) {
  return this._super(type, id, record) + '/';
  }
});

The service worker registers when I open the app:

(function () {
  'use strict';

  self.addEventListener('install', function installEventListenerCallback(event) {
      return self.skipWaiting();
    });

    self.addEventListener('activate', function installEventListenerCallback(event) {
      return self.clients.claim();
    });

  const FILES = ['assets/connect.css', 'assets/connect.js', 'assets/connect.map', 'assets/failed.png', 'assets/passed.png', 'assets/test-support.css', 'assets/test-support.js', 'assets/test-support.map', 'assets/tests.js', 'assets/tests.map', 'assets/vendor.css', 'assets/vendor.js', 'assets/vendor.map'];
  const PREPEND = undefined;
  const VERSION$1 = '1';
  const REQUEST_MODE = 'cors';

  /*
   * Deletes all caches that start with the `prefix`, except for the
   * cache defined by `currentCache`
   */
  var cleanupCaches = (prefix, currentCache) => {
    return caches.keys().then((cacheNames) => {
      cacheNames.forEach((cacheName) => {
        let isOwnCache = cacheName.indexOf(prefix) === 0;
        let isNotCurrentCache = cacheName !== currentCache;

        if (isOwnCache && isNotCurrentCache) {
          caches.delete(cacheName);
        }
      });
    });
  };

  const CACHE_KEY_PREFIX = 'esw-asset-cache';
  const CACHE_NAME = `${CACHE_KEY_PREFIX}-${VERSION$1}`;
  const CACHE_URLS = FILES.map((file) => {
    return new URL(file, (PREPEND || self.location)).toString();
  });

  /*
   * Removes all cached requests from the cache that aren't in the `CACHE_URLS`
   * list.
   */
  const PRUNE_CURRENT_CACHE = () => {
    caches.open(CACHE_NAME).then((cache) => {
      return cache.keys().then((keys) => {
        keys.forEach((request) => {
          if (CACHE_URLS.indexOf(request.url) === -1) {
            cache.delete(request);
          }
        });
      });
    });
  };

  self.addEventListener('install', (event) => {
    event.waitUntil(
      caches
        .open(CACHE_NAME)
        .then((cache) => {
          return Promise.all(CACHE_URLS.map((url) => {
            let request = new Request(url, { mode: REQUEST_MODE });
            return fetch(request)
              .then((response) => {
                if (response.status >= 400) {
                  throw new Error(`Request for ${url} failed with status ${response.statusText}`);
                }
                return cache.put(url, response);
              })
              .catch(function(error) {
                console.error(`Not caching ${url} due to ${error}`);
              });
          }));
        })
    );
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(
      Promise.all([
        cleanupCaches(CACHE_KEY_PREFIX, CACHE_NAME),
        PRUNE_CURRENT_CACHE()
      ])
    );
  });

  self.addEventListener('fetch', (event) => {
    let isGETRequest = event.request.method === 'GET';
    let shouldRespond = CACHE_URLS.indexOf(event.request.url) !== -1;

    if (isGETRequest && shouldRespond) {
      event.respondWith(
        caches.match(event.request, { cacheName: CACHE_NAME })
          .then((response) => {
            if (response) {
              return response;
            }
            return fetch(event.request);
          })
      );
    }
  });

  const VERSION$2 = '1';
  const PATTERNS = ['http://localhost:8000/api/v1/(.*)'];

  /**
   * Create an absolute URL, allowing regex expressions to pass
   *
   * @param {string} url
   * @param {string|object} baseUrl
   * @public
   */
  function createNormalizedUrl(url, baseUrl = self.location) {
    return decodeURI(new URL(encodeURI(url), baseUrl).toString());
  }

  /**
   * Create an (absolute) URL Regex from a given string
   *
   * @param {string} url
   * @returns {RegExp}
   * @public
   */
  function createUrlRegEx(url) {
    let normalized = createNormalizedUrl(url);
    return new RegExp(`^${normalized}$`);
  }

  /**
   * Check if given URL matches any pattern
   *
   * @param {string} url
   * @param {array} patterns
   * @returns {boolean}
   * @public
   */
  function urlMatchesAnyPattern(url, patterns) {
    return !!patterns.find((pattern) => pattern.test(decodeURI(url)));
  }

  const CACHE_KEY_PREFIX$1 = 'esw-cache-fallback';
  const CACHE_NAME$1 = `${CACHE_KEY_PREFIX$1}-${VERSION$2}`;

  const PATTERN_REGEX = PATTERNS.map(createUrlRegEx);

  self.addEventListener('fetch', (event) => {
    let request = event.request;
    if (request.method !== 'GET' || !/^https?/.test(request.url)) {
      return;
    }

    if (urlMatchesAnyPattern(request.url, PATTERN_REGEX)) {
      event.respondWith(
        caches.open(CACHE_NAME$1).then((cache) => {
          return fetch(request)
            .then((response) => {
              cache.put(request, response.clone());
              return response;
            })
            .catch(() => caches.match(event.request));
        })
      );
    }
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(cleanupCaches(CACHE_KEY_PREFIX$1, CACHE_NAME$1));
  });

  const VERSION$3 = '1';
  const INDEX_HTML_PATH = 'index.html';

  const CACHE_KEY_PREFIX$2 = 'esw-index';
  const CACHE_NAME$2 = `${CACHE_KEY_PREFIX$2}-${VERSION$3}`;

  const INDEX_HTML_URL = new URL(INDEX_HTML_PATH, self.location).toString();

  self.addEventListener('install', (event) => {
    event.waitUntil(
      fetch(INDEX_HTML_URL, { credentials: 'include' }).then((response) => {
        return caches
          .open(CACHE_NAME$2)
          .then((cache) => cache.put(INDEX_HTML_URL, response));
      })
    );
  });

  self.addEventListener('activate', (event) => {
    event.waitUntil(cleanupCaches(CACHE_KEY_PREFIX$2, CACHE_NAME$2));
  });

  self.addEventListener('fetch', (event) => {
    let request = event.request;
    let isGETRequest = request.method === 'GET';
    let isHTMLRequest = request.headers.get('accept').indexOf('text/html') !== -1;
    let isLocal = new URL(request.url).origin === location.origin

    if (isGETRequest && isHTMLRequest && isLocal) {
      event.respondWith(
        caches.match(INDEX_HTML_URL, { cacheName: CACHE_NAME$2 })
      );
    }
  });

}());

This is how network requests appear in Chrome:Network request while offline

I assume the problem is in the configuration of ember-service-worker-cache-fallback. But I'm not quite sure about that. Any idea or link to a working example is welcome. I didn't find a lot about ember-service-worker-cache-fallback so far.

Thanks!




Ember : How can i create routes and controllers at runtime?

I have to dynamically create routes and controllers based on the parameters i receive at run time. I cannot create routes beforehand because there are simply too many routes that use the same code with minor differences. Is this possible? If so, how?




mardi 30 mai 2017

serve a localhost from a different port in EmberJS

Normally, when a user calls

ember serve

The local host is always 4200 by default. It would be nice if I could specify a different port so that I could have two ember web apps running. Is it possible to have a ember serve a different port?

The reason I care is that I'm using one of my web apps to help me build the other, and it would be convenient to have them both running at the same time so that I don't keep going back and forth with my builds.




How to Update JWT token from response header in ember-simple-auth session

I am using ember-simple-auth & ember-simple-auth-token to maintain session on Ember. I do not want to use the refresh-token approach, instead would like to receive a new jwt token in the response header from every service request.

how can i keep my session alive by updating the jwt token in the session every time I receive a response from the server?




ember-cli-mirage response headers are missing from XHR object

Trying to understand the inconsistency in the response between using my api vs ember-cli-mirage.

I have a handler making a POST request to authenticate a user. The expected parameters for the handler are response, status and xhr. Using my API I receive what I'd expect- response is the data, status is the statusText and xhr is the xhr object. However using ember-cli-mirage everything comes under response (kind of), and status and xhr are both undefined.

Snippets of my code are below:

mirage/config.js

this.post(URI.AUTH_SIGN_IN, function(db, request) {
  const responseHeaders = {
    'access-token': 'abcxyz123',
    'client': 'foobarbaz',
    'token-type': 'Bearer',
    'expiry': '1497364419',
    'uid': 'user@example.com'
  };

  const user = {
    data: { id: 1, type: 'user', attributes: { uid: 'user@example.com', email: 'user@example.com', name: 'John Doe', provider: 'email' } }
  };

  return new Mirage.Response( 200, responseHeaders, user );
});

authenticators/devise.js

authenticate(identification, password) {
  ...
  this.makeRequest( credentials ).then(function(response, status, xhr) {
    // persists the five headers needed to send to devise-token-auth
    // with mirage; response = Response {type: "default", status: 200, ok: true, statusText: "OK", headers: Headers…}, status = undefined, xhr = undefined
    // with actual api; response = Object {data: Object}, status = "success", xhr = Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function…}
   });
}

I believe I'm doing it all correctly, but I've been known to be wrong :). Any help is much appreciated.




How to make route parameters optional in Ember.js?

In Ember.js, given these routes:

this.route('chefs', { path: ":country/chefs"});
this.route('recipies', { path: ":country/recipies"});

I am required to put the positional params in the link-to component, like:

Mexico Chefs

How can I avoid specifying some params in all my link-to components?

I'm thinking the 'chefs' route could use a default parameter coming from a service. But how? Any other ideas?

Here is a Twiddle: http://ift.tt/2rluUIG




(Ember-cli-g-maps) - Changing markers properties dinamically

This is my first question here, so I hope do it in the right way.

I'm trying to use ember-cli-g-maps in my project. The tool is great, but I'm having great dificulties in making one of my requirements work.

The chalange is: I create a set of markers setting the "draggable" property to false.

Template



Controller

for (let i=0; i< data.stops.length; i++)
{
    let stop = data.stops[i];
    markers.pushObject(
              {
                id: stop.id,  // Recommended
                lat: stop.coordinate[0],
                lng: stop.coordinate[1],
                draggable: false,
                icon: 
               });
  }

The markers are added correctly in the map.

But I want to make all markers draggable when the user press a button .

This is how I trying to do it.

enableMarkersDrag()
{
    for (var i=0; i<this.get('markers').length; i++)
    {
      this.get('markers')[i].draggable = true;
    }
},

This doesn't work immediatelly, but it does when I make some change in the "markers" array, adding or removing an item. It is a MuttableArray.

I understand why. This is because the observer is observing the array, not the properties inside the array.

But I believe that 'add' and 'remove' an item just to trigger the observer is not the right way to do it. Do you guys know the clean way of doing this?

Thanks in advance;




Handlebar helper to iterate every X number of items

I am iterating over a list of items:


    ...do stuff...


But I want to grab every 4 items. Something like this:


    ...do stuff...


I tried this, and it doesn't work. Is there a way to grab every X items? If so, is the solution scalable?




Rails 5/Ember-CLI-Rails - NoMethodError (private method `require' called for #

In Rails 5, we're receiving NoMethodError (private method 'require' called for #<ActiveSupport::HashWithIndifferentAccess when calling something simple in a controller like params.require(:key). This endpoint is triggered from an Ember CLI rails page (not sure if it's the reason).

I know it's been deprecated, and am suspecting some middleware, but I've removed a lot and so far it hasn't helped.

rake middleware yields:

Michaels-MBP-2:mvp mycomp$ rails -v
rake Rails 5.0.1
Michaels-MBP-2:mvp mycomp$ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]
Michaels-MBP-2:mvp mycomp$ rake middleware
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use RequestStore::Middleware
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use Airbrake::Rack::Middleware
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
use ParamsTester
use Rack::Cors
run My::Application.routes

ParamsTester is my middleware trying to determine when params is being converted to a hash, which looks like this in lib/params_tester.rb and is returning PARAMS NOT SET

VALID_LOG_LEVELS = [:debug, :info, :warn, :error, :fatal, :unknown]

class ParamsTester
  def initialize app, log_level
    @app = app
    # Default to :info log level if the user sets an invalid log level.
    @log_level = VALID_LOG_LEVELS.include?(log_level) ? log_level : :warn
  end

  def call env
    dup._call env
  end

  def _call env
    request_started_on = Time.now
    @status, @headers, @response = @app.call(env)
    request_ended_on = Time.now

    Rails.logger.send(@log_level, '=' * 50)
    Rails.logger.send(@log_level, "Request delta time: #{request_ended_on - request_started_on} seconds.")
    begin
      Rails.logger.send(@log_level, 'PARAMS: ' + request ? request.parameters.class : ' NO REQUEST PARAMS')
    rescue
      Rails.logger.send(@log_level, 'PARAMS NOT SET')
    end
    Rails.logger.send(@log_level, '=' * 50)

    [@status, @headers, @response]
  end
end




Rails and ember with acts-as-taggable-on. How to handle relationships in JSONAPI endpoint?

I have a Rails 5 (or 4) application and I need a good tag system.

  • First question: is acts-as-taggable-on still a good choice?

This is my code:

class User < ActiveRecord::Base
  acts_as_taggable_on :tags
end

class UsersController < ApplicationController
  def user_params
    params.require(:user).permit(:name, :tag_list)
  end
end

@user = User.new(:name => "Bobby")

I'm able to add and remove with this (from Rails console or code):

@user.tag_list.add("awesome")
@user.tag_list.remove("awesome")

  • Second question: how can I handle relationship?

I'll explain it better: let's say I'm using Ember (or also Angular or others with JSONAPI, it's the same for my question), and I'm using ActiveModelSerializer 0.10.x:

app/models/user.js:

import DS from 'ember-data';

export default DS.Model.extend({
  tags: DS.hasMany('tag')
});

app/models/tag.js:

import DS from 'ember-data';

export default DS.Model.extend({
  users: DS.hasMany('user')
});

app/routes/myroute.js:

let user = this.get('store').peekRecord('user', 1);
let tag = this.get('store').createRecord('tag', {
  user: user
});
tag.save();

Now I have the problem: how can I say Rails to save this new tag (in taggings table I think)?

Generally when I have a relationships to handle in Ember I create a JSONAPI endpoint in Rails and with foreignKey and CREATE api I save all and it works good. But with acts-as-taggable-on I don't know how to save.

Maybe I have to generate a new endpoint for taggings and write my own code in a controller to handle savings for tags? Really? Maybe i'm missing something...




application view/component in ember-cli 2.13

I have recently started a new project with the most recent ember-cli (v 2.13 as stated in the topic). I am rather set on generating clean semantic html, and as such don't like the extra div.ember-view that the application generates.

Before I could create the app/views/application.js file with following content:

import Ember from 'ember';
export default Ember.Component.extend({
    tagName: ''
});

It simply used the component as application view and got rid of the root tag, however it doesn't seem to work anymore. In fact when debugging the resolver "view:application" doesn't show up at all. Is there a new way of solving this situation? Afaik routable components are not exactly in yet, are they?

Granted, my last ember project was using ember-rails (with ember 2.7), now I'm going for a pure ember-cli project, so a few things might indeed have changed.

How can the same effect be achieved now? Is it just a case of adding a special rule to resolver? Or maybe it can be reached otherwise? I learned that ember docs can be rather lacking when it comes to new obscure features...




lundi 29 mai 2017

Using versus

This is a pretty newbie question. However, in EmberJS, I've found that both of the methods work for linking to the blog page in my application.

<p> See my blog</p>
<a href="posts"> See my blog</a>

Is it better to use in EmberJS? How come?




EmberJS : Call parent class function from child class init method

I have a parent class

MyBaseClass = Ember.Object.extend({
  getData:function() {
    return someData;
  }
})

and a child class that when created needs to call a function in parent class

MyChildClass = MyBaseClass.extend({
  sampleData:[],
  init:function(){
    Ember.set(this, 'sampleData', this.getData());
  }
})

My problem is, when i run this code i get "Uncaught TypeError: this.getData is not a function".

Any idea why this is happening? Or fix to this.




Ember route activate method not called when transition to already active/loaded route

I am facing a scenario that i have a button in side bar with link to some route. first time i click that button, the activate method of the destined route and init method of destined controller is called, but the second time i click that button while that route is active, no hook or method is called

is there any hook that is called for route or controller even when the route is active?




dimanche 28 mai 2017

Ember Multiselect onchange

I have an Ember HBS template with a multiselect that I need to update the model onchange.

For regular selects, I used the following

<select id="scCalibration" onchange=>

But for the multiselect, what I need is a comma delimited list of selected values updated in the model. I'd prefer not to use a third party library like Ember-Power-Select if possible. I can't seem to figure it out...




samedi 27 mai 2017

ember serve and live reload results in "cannot GET /foo"

TL;DR: ember serve -> navigate to route /foo -> change template -> live reload -> "cannot GET /foo"

I have an existing corporate app that had at one point used ember-pagefront to test on pagefront, but we have since moved on to hosting it ourselves.

Since I know we weren't using pagefront, I wanted to remove config/deploy.js (which just referenced pagefront), so I thought I should also uninstall pagefront. So, I executed npm remove ember-pagefront. This completed without incident.

However, as soon as the uninstall completed, I had some weird funnel errors on ember serve running in another console for this project, so I did the obvious: CTRL+C and then ember s again.

That's when the fun started.

The server started, no errors, I hit http://localhost:4200/, the index route redirected to my app's proper start page as usual (/contacts), and I was happy - the world looked good.

However, as soon as I made a change to one of the projects files which triggered the live reload, I received following cryptic error:

Cannot GET /contacts

What? Weird. I tried everything:

  • Removed node_modules and did npm install again - no change
  • Checked github for the previous package.json file, did a diff - the ONLY line that changed was the ember-pagefront line, so I reinstalled ember-pagefront - no change
  • Download the previous rev of the app (from right before I did the npm remove ember-pagefront) from private github rep, appros setup (npm install && bower install && ember s) - exact same error
  • Tried a different browser (Firefox) - same error
  • Tried an incognito tab in Chrome - same error
  • Cleared cache - same error

  • Checked the running production server (running the same SHA1 of the code I checked out from before removing pagefront) - and production runs fine (but it's being served via nginx, not ember s obviously)

So what in the world should I be checking? It's like ember s all of a sudden forgot how to properly route 404s. Any ideas?




vendredi 26 mai 2017

CircleCI with Rails server and ember app

I'm working on a Rails application, that uses ember as front-end framework for the client side within the application. I use Capybara on CircleCI to run the tests.

I have a lot of end-to-end tests, which make the build time very slow. I have found that the problem could be because it builds ember application for every spec file separately.

Is there anyone who knows if I can build the whole application once (somehow), and use that as the test server, to speed up the build. Or some other method/suggestion to improve the speed of my build.

Thanks




ember-cli-imagemin lossyPNG ImageMin.pngquant is not a function

I'm trying to enable the lossyPNG property in the ember-cli-imagmin addon to create a small file size for my .pngs. My EmberApp in ember-cli-build.js includes imagemin like so:

imagemin: {
  interlaced: true,
  optimizationLevel: 3,
  progressive: true,
  lossyPNG: true,
  pngquant: {
    speed: 1,
    quality: 80
  }
}

The dependencies object in my package.json includes:

{ ...
  "ember-cli-imagemin": "0.4.0",
  "imagemin": "3.2.2",
  "imagemin-pngquant": "4.2.2",
  ...
}

However, whenever I run ember build I get the following error:

The Broccoli Plugin: [object Object] failed with:
TypeError: ImageMin.pngquant is not a function

This error points me to this line in broccoli-imagemin. If I set lossyPNG to false in ember-cli-build.js then I receive no error, but my pngs could be optimized further based on the results from pagespeed. What am I missing to be able to use pngquant to further optimize my png images?




Create new ember project with no internet connection?

Can it be possible to run ember new foo without an internet connection?
Project initialization involves fetching a number of resources from npm; is it possible to cache these ahead of time so that an internet connection is not necessary?




Why does an ember addon using a bower dependency needs to override normalizeEntityName?

You are developing an ember add-on that internally needs a bower package. When you install this add-on in an ember project, you need the bower package to be added to the project's bower dependencies so that your add-on can run.

Ok - easy enough, we just need a default blueprint and a call to afterInstall

module.exports = {
  normalizeEntityName: function() {}, // no-op since we're just adding dependencies

  afterInstall: function() {
    return this.addBowerPackageToProject('a-bower-package');
  }
};

Why is the override to normalizeEntityName necessary? At first I had missed adding this to my blueprint, and spent an ungodly amount of time trying to pinpoint why it was not installing the bower dependency as I was expecting.

I haven't seen a satisfactory answer anywhere, the ember-cli guide explanation doesn't address this and the closest resource I have found was this article, where all it says about the subject is this:

The hero we all need, even if the reason we deserve it can be a bit opaque, normalizeEntityName needs to be overridden as a noop inside of the default blueprint in order for ember g your-addon-name to even work. Just set this as the first property of your exported object, and forget all about it (but never forget it in the future 😀):

So... why do we need it?




How do I go about creating an article/review template in a single page application?

I've been thinking about this for a while, trying to search the web, but every search query that contains the word 'template' inevitably returns endless results of sites that want to ram their (crappy) pre-fab html designs down your throat.

I'm looking for a consistent way of creating a template to show reviews on a website, preferably while not looking identical, in a SPA environment, Emberjs to be precise.

Even if I have one template, with let's say, 3 blocks of text with each a picture in between, I still need to consider whitespace and paragraphs. Something that's not really possible while operating from the crud section on the website, it's just plain text that goes into the block sections.

Suppose I have a lenghty review, and I want to add a fourth block, or an extra picture, I'll have to update the ember template, possibly ruining all previous reviews that are already posted.

If I were to do this in .NET, I'd just make a page for every review. Is this how I should be doing it on SPA's ? A new route for every review, ending up with hundreds of components/routes in the long run? Both scenario's aren't CRUD friendly though, I'll always have to go back into the code to add a page/route.

I now have the simplest of setups (pseudo-code):


 






Anyone with advice/experience on this matter ? Much appreciated ! :)

EDIT 1: Come to think of it... something akin to when I create my question on SO, would help. Save the review as a whole, pictures and formatting included, but is this even possible with Firebase ?




Dynamically updating query params

In ember.js how do you dynamically update a query param?

export default Ember.Controller.extend({
    myQuery: "test",

    queryParams: ["myQuery"],

    actions: {
       click() {
          this.set("myQuery", "update query param");
      }
    }
});


export default Ember.Route.extend({
  queryParams: {
    myQuery: { refreshModel: true }
  },
  model(params) {
    console.log(params)
  }
});

When the action is fired the model hook should be called again, unless I am wrong?

Please find an example here, navigate to the /test route and click the button. Inside the console you can see that the model hook is not fired again.




Ember Need data from one promise in the model for another query in model()

So the model for this app for all routes is set up like this:

  model(params) {
    let config = this.get('store').findRecord(params.config_type, params.config_id);
    let c = Ember.RSVP.hash({config});
    console.log('aa');
    console.log(c);
    let devices = this.get('store').findAllOfType('device', ENV.CFG_TYPE[params.config_type]);
    let licenses = this.get('store').findAll('license');

    return Ember.RSVP.hash({
      configType: params.config_type,
      config: config,
      devices: devices,
      licenses: licenses
    });
  },

I need to change the devices query to use a secondary criteria which is held inside the config which is returned by the first query. The only problem is this isn't resolved and doesn't have the data in it.

When I log out c I see initially undefined for the _results property, then when I expand it, it shows the config object.

I realize this is because the promise isn't resolved yet, and is resolved some time in the future, but I need that data to get the right devices. I don't want to pass them as query params as these are two separate pieces of data I need.

I was thinking I could do .then() on the config line and return the Ember.RSVP.hash in there but that would return it to model() and I am not sure how I would return it from there, or if it would even return from there, or if config would now be equal to the RSVP hash and not the config promise/object.

My options are:

  1. Find a way to pass it somehow from one route, which has the same config object already in the model, to this one, without using query params

  2. Setup the entire model in the callback from the first query somehow (the findRecord() one)

Totally clueless on how to do it either way.




Managing user roles in emberjs?

I have a nodejs api as shown below

route.post("/token",function(req,res){
    authLib
        .checkForm(req.body)
        .then(authLib.findUser)
        .then(authLib.isValidUser)
        .then(authLib.authenticate)
        .then(authLib.genToken)
        .then((token)=>{
            res
                .status(200)
                .json({'access_token': token});
        })
        .catch((err)=>{
            res
                .status(400)
                .json({'error': err.message});
        });
});

The model for user contains a field with user role. Each user role has a different dashboard. I have implemented ember-simple-auth with oauth2-password-grant and the template for dashboard is as shown below


    
    

    
    


The problem is how can i distinguish between the user roles. One method could be to use ajax requests to fetch role but that would mean an additional XHR request for all views. Also another problem with using XHR in Ember.$ is that the authorization token is not attached to request. What is the best way to solve this issue ?




In Ember how to exclude single from vendor folder from minifying

I got situation like, I included morris.js file from vendor folder, and configured in ember-cli-build.js file but then my specific modified feature is working in development but not in the production build.

I am using ember-cli-babili for minification. either I should fix which minification part causing the issue or I should remove this file alone from minification.

Is this possible? any guidance is appreciated.




How to test component methods in Ember.js?

I have component with one method and service, which can run functions for some components.

export default Ember.Component.extend({
  foo: false,

  bar() {
    this.set('foo', true);
  },

  someService: Ember.inject.service('some-service'),

  didInsertElement: function () {
    const someService = this.get('someService');
    someService.registerComponent(this);
  },
});

export default Ember.Service.extend({
  components: [],
  registerComponent: function (component) {
    let components = this.get('components');
    components.push(component);
  },
  runBar(index) {
    let components = this.get('components');
    components[index].bar();
  }
});

1) How can I write tests for bar() method?

2) And also how can I write tests for this service?

3) Or how can I refactor this approach?




jeudi 25 mai 2017

Ember computed alias on array firstObject not working

I have this computed property alias in my component:

firstElement: Ember.computed.alias('myArray.firstObject')

This works in development, but doesn't update in production mode.

This code though works in both development and production:

firstElement: Ember.computed('myArray.[]', function() {
  return this.get('myArray.firstObject');
}

Is the alias macro not allowed on firstObject , lastObject, etc..?

It also seems weird that in works in development but not in production mode.




How return the type of polymorphic relationship?

I have a participant model that return a polymorphic relationship called participable, I need return the type of relationship instead of type participable. I am using at frontend Ember.

class ParticipantSerializer < ApplicationSerializer # :nodoc:
  attributes :id

  belongs_to :dispute
  belongs_to :participable, polymorphic: true
end




POST request to API from Ember often fails with 'The adapter operation was aborted Error'

I'm writing an Ember tutorial that I'd like to run on top of a very simple API I've created in Flask. PUT, DELETE, and GET requests made from ember-data behave as expected. The POST request throws an error and does not complete. The POST Ajax request is canceled before it's sent.

This behavior is intermittent. If I set a breakpoint and follow it through the Ember internals then by the time I'm done, the request will often succeed. When running the API locally the error is thrown but the new user is still written to the database. So this feels like client-side async weirdness but I'm lost on how to proceed.

I can successfully complete a POST request using curl, from postman and from the console in Chrome using JQuery. The preflight OPTIONS request succeeds. My API is set up for CORS and returns an 'Access-Control-Allow-Origin' header of '*' and an 'Access-Control-Allow-Headers' of 'content-type'. There is no content security policy set up on the Ember app.

My API is here:

GitHub: http://ift.tt/2r2GU1j

My Ember app is here:

GitHub: http://ift.tt/2s0rVCz




ember-pouch: does not load hasMany relationship when the belongsTo side is polymorphic

I have an ember-data app that uses the ember-pouch adapter for local & remote storage.

I am unable to load hasMany relationships when the belongsTo side is polymorphic. I've played with async: true/false and donstsave: true/false options on the hasMany side, to no avail.

The setup:

  • post can have many comments.
  • comment can have many comments.
  • comment belongs to commentable.
// app/models/post.js
import DS from 'ember-data';
import { Model } from 'ember-pouch';

export default Model.extend({
    DS.hasMany('comment', { inverse: 'commentable' });
});

// app/models/comment.js
import DS from 'ember-data';
import { Model } from 'ember-pouch';

export default Model.extend({
    DS.belongsTo('commentable', { polymorphic: true });
    DS.hasMany('comment', { inverse: 'commentable' });
});

The Problem

Calling post.get('comments') loads nothing. If comments are loaded into the store separately, however, then post is able to correctly render comments:

// In the console (being mindful that `post.get('comments')` returns a promise)

const post = store.findRecord('post', '123');
post.get('comments').get('length'); // => 0

store.findAll('comment');
post.get('comments').get('length'); // => 12




Ember helper that returns the resolved value of a promise

How can I get this helper to return the result of a promise?

// helpers/city-temperature.js

import Ember from 'ember';

export default Ember.Helper.extend({
  weather: Ember.inject.service(),
  compute(params) {
    let location = params[0];
    let temperaturePromise = this.get('weather').getTemperaturePromise(location);
    return temperaturePromise.then((value)=>{
      return value;
    });
  }
});

I modeled it after code from this discussion. It's retrieving the value from the remote API but I'm not able to get it to display in the component. And I want to do it without passing a DOM element around.

The complete app code is here.




Ember component computed function does not rerun when data changes

I have stored a string value within a computed property like so:

clientId: Ember.computed.oneWay("_clientId")

where _clientId is defined as a property on the object like so:

export default Ember.service.extend { _clientId: null, clientId: Ember.computed.oneWay("_clientId"), updateId() {this.set("_clientId", "fe48822d-bf50-44a1-9ce0-61b06504d726"); } }

I then have a component with a computed property like so:

chartData: Ember.computed("data", function () {
    const data = this.get("data");

    const clientId = this.get("session").get("clientId");
    console.log(clientId);

    if (data && data.get("left") !== undefined && data.get("right") !== undefined) {
        return data;
    }

    this.set("_chartDisplayData", null);
    return null;
})

When I called updateId, i expected the chartData function to be re-run as the value of the clientId is changed (i verified that the value gets changed for clientId). However, the chartData function never re-runs, why is this?




How to get the latest version of Ember-Data, Ember-CLI, and Ember.js from Ember-CLI

I know how to check what my current version is

How to tell ember.js and ember-data version from ember-CLI?

But if I want to check which version I'm on from Ember-CLI, what is the best way to do this? I know I can google it but it would be nice if I could get the latest version straight from my command-prompt.




Ember Nested Routes Break Named Outlet

I have a Parent route named engineering. Every route extends a Base.js route which renders the default template as well as another custom one into the named outlet:

renderTemplate: function (controller) {
    this.render();

    this.render('page-title', {
        outlet: 'pageTitle',
        controller: controller,
    });
},

There is a engineering.hbs parent template which contained two outlets. The Main and another {outlet 'pageTitle'}}.

This works perfecly fine for routes like /engineering/index and engineering/someothersite, but the pageTitle outlett just doesn't render at all for routes like engineering/college/courses/description.

Any Suggestions, or perhaps even a better way of passing data from a child route to the parent template?




mercredi 24 mai 2017

Ember Select to Update Model onChange

I have an Ember HBS template form with input and select fields. Input fields use a 'value' argument set to model.someField. When a user changes the input value, the model also gets changed and then shows there are changedAttributes staged.

I want to do this exact same thing with a select, but when I change the select value, the model.someField isnt getting updated automatically. What's the right way to do this?

I'm using Ember 2.9.




how to reject promise inside a then

I want to be able to reject the entire promise chain if anyone of the promise fails. I want to "catch" this rejection and send an error notification. I have the following code:

let reportMetaData = api.ajaxGet(api.buildV3EnterpriseUrl('reports' + '/' + params.report_id))
                        .catch(error => {
                          if (error.status === constants.HTTP_STATUS.GATEWAY_TIMEOUT) {
                            this.notify.error(this.translate('reports.report_timedout'), this.translate('reports.report_timedout_desc'));
                          } else {
                            this.send('error', error);
                          }
                        });

let aggregateData = reportMetaData.then(success => {
                                                      try {
                                                        return api.xmlRequest('GET', success.aggregationUrls.elements[0].url);
                                                      } catch(error) {
                                                        return Promise.reject();
                                                      }
                                                    }).then(rawData => {
                                                      try {
                                                        return JSON.parse('{' + rawData + '}');
                                                      } catch (error) {
                                                        return Promise.reject();
                                                      }
                                                    }, error => Promise.reject(error));

let aggregateReport = aggregateData.then(data => {
                                                    if (!data || !data.report) {
                                                      return Promise.reject();
                                                    }
                                                    return data.report;
                                                 }, error => {error => { this.notify.error(this.translate('reports.report_timedout'), this.translate('enterprise.reports.malformed_report'))}});

I want the simplest way to reject the entire promise to fail if anyone promise fails. How do I do that from inside the then function?




How do frameworks update the DOM WITHOUT a Virtual DOM?

I have been Researching React's virtual DOM(how it works) for a while now, and so far I have understood the following:

-It has an in-memory DOM representation at all times

-When something changes in the application/component the virtual DOM creates another representation of component's/application's DOM - this time how it should look like

-It "diffs" them to find the minimum differences that need to be updated in the real DOM

-It updates the real DOM

I wanted to know if other frameworks update DOM and detect changes differrently and if they do - how.




Cookies not sent to tomcat server when ajax call is made from ember server

I have a ember server running on localhost port 4200 and a JAVA backend API server running on localhost port 8080. I use java's jSession for identifying user and for maintaining user sessions. cookies values are set as HTTP only from tomcat server.

Now when i make a AJAX call to Java server running on 8080 from ember running on 4200, cookies set by java session is not sent to the API server. How do i enable the ember to send java set cookies along with the AJAX calls?




Handlebars lookup helper to build dynamic tables

I would like to build a dynamic table using handlebars. I think I have to use lookup helper to achieve my wanted result. I am having some trouble using the lookup helper and the documentation is rather poor.

An example of my object looks like this:

{
headers:[
  0:"name",
  1:"brand",
  2:"type",
  3:"rating",
  4:"edited"
]
tableContent:[
  0:{
     contentName:{
        name:"Fanta",
        brand:"Coca-Cola Company",
        type:"Soda",
        rating:"3",
        edited:"2017-05-24"}
    }
]
}

Handlebars template:

<script id="itemTemplate" type="text/x-handlebars-template">
  <table id="table" class="bordered highlight centered">
    <thead>
      <tr>
        
        <th></th>
        
      </tr>
    </thead>
    <tbody>
      <tr>
        
        
        <td></td>
        
        
      </tr>
    </tbody>
  </table>
</script>

The reason I can't simply do <td> contentName.name </td> and so on, is that the user can create their own columns in the database, so I would have no way of knowing the property names beforehand.




Refreshing a parent route's model when creating new record in a child route?

I have a parent route that lists a number of objects and a child route that allows users to create new objects in a modal dialog. Something like:

// Parent route (app.colours)
export default Ember.Route.extend({
    model() {
        return this.store.findAll('colour');
    },
}

and a child route that allows you to add new objects:

// Child route (app.colours.create)
export default Route.extend({
    model() {
        return this.store.createRecord('colour');
    },
    actions: {
        save(colour) {
            color.save().then(() => this.transitionTo('app.colours'));
        }
    }

I notice that when I successfully create a new colour record and transition back to the parent route, the new record isn't in the list as the parent route's model hasn't been refreshed.

How can I tell the parent route to refresh its model from the child route?




Ember-simple-Auth addon throws error

I just installed ember-simple-auth (version 1.3.0) in my application. Before insalling addon, the application is working fine but after installing it throws the following error:

Uncaught TypeError: (intermediate value)(intermediate value).on is not a function
at Module.callback (vendor.js:71693)
at Module.exports (vendor.js:123)
at Module._reify (vendor.js:157)
at Module.reify (vendor.js:144)
at Module.exports (vendor.js:121)
at requireModule (vendor.js:38)
at Class._extractDefaultExport (vendor.js:97027)
at Class.resolveOther (vendor.js:96724)
at Class.superWrapper [as resolveOther] (vendor.js:33300)
at Class.resolve (vendor.js:15968)

I tried to remove ember-disable-prototype-extensions from package.json of added addon as per this Ember CLI Hook/Event Error. Still didn't work.

Any help is much appreciated




mardi 23 mai 2017

check if a ember object exists on the clients browser?

Say there exists some express and emberjs website 'www.example.com'. The backend is a data centric api with a single route to serve static files (emberjs application). if a client visits 'http://ift.tt/2qTI8vJ', this route returns a JSON response. How can you check if emberjs is loaded in the clients browser?




One-way bound inputs in Ember?

Ember's default helper creates a two-way binding. What's the state-of-the-art way to create an input element that is only one-way bound?

A Google search for "ember one-way input" yields several add-ons:

but do I need an add-on?




Refresh / Reload ember route from a component

I have a component, that's actually a modal dialog. When I am done with that dialog and press the "Ok" button, I want to stay on the stay page from where I opened that dialog. Which isn't difficult.

But the problem is that the dialog changes the data (I am getting data through a REST call) so I need to refresh the route that I already am on to reflect the data changes.

Since, I am calling it from a component, I don't have Route so can't call route.refresh().

I tried to get the router:

this.set('router', Ember.getOwner(this).lookup('router:main'));

and did transition to the same page:

_this.get('router').transitionTo('my-route')

But since the route hasn't changed (I only opened a dialog), transitionTo doesn't get triggered!

Is there a way I can force trigger transitionTo or refresh the page that I am on?

Thank you!




Add parent hierarchy recursively to Ember Object

I'd like to add parent properties recursively to an Ember Object. Something like...

var ParentMixin = Ember.Mixin.create({ /* Not sure what would go here */ });
var EmberObjectWithParentMixin = Ember.Object.extend(ParentMixin, {});
var obj = EmberObjectWithParentMixin.create({
  prop1: {
    prop2: {}
  }
});

So then the behavior I'm looking for is...

obj.prop1.prop2.parent === obj.prop1

I'm open to solutions that do not involve a mixin, that's just where my head is going at this point.




Ember locks up on afterModel: ()

So I have searched the web up and down and can't find anything about this. Basically I have tried many different times to use the afterModel hook in routes to no avail because it hangs the application.

First use case was to prevent users from going to routes that were not permissible during certain situations. This worked fine, I aborted the transition no problem. The problem is when the conditions of those if statements are NOT true and the hook is expected (by me) to just exit and then render the page. Nothing happens. Just sits there forever.

This is something where doesn't matter what code I have in there, it simply does not work.

This:

afterModel: function(model, transition) {
},

Locks up the app. I could find nothing on any tutorial or definition of afterModel that specifies requiring you to return anything though I've seen examples where they've returned something.

beforeModel doesn't have this problem.




Unable to modify Ember mirage fixture from within acceptance test

I have a fixture create which looks somewhat like this.

path => mirage/fixtures/people.js

 export default {
      'people': [
        {
          'id': 1,
          'name': 'Ram',
         },
         {
          'id': 2,
          'name': 'Raja',
         }
       ]
    }

Inside my acceptance test I'm doing server.create('people'); which successfully returns this array of object. But within my test, I want to modify this people array and add, suppose another object { 'id': 3, 'name': 'John', }

Note: I dont want to use factories as I dont want all datas to be dynamically generated, so I want to take this array from fixtures, push my new object into this array and then return it. What is the correct way to do it?

Note2: Don't suggest adding this object in fixtures itself, because I want to dynamically add items to the fixture based on conditions in my test.




Access XMLHttpRequest from Ember Data

I am developing a web application in Ember 2.3.0 and while doing some cross-browser testing, it became apparent the slowness of the application for IE 11. Doing some measurements on the IE developer's console seems that the DOM onreadystatechange event eats up to 100% CPU for a period of time, which could be a leak.

I found this article: http://ift.tt/2rdm3t3 that despite being old it encouraged me to test the approach of nulling the onreadystatechange event in case it is a memory leak.

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
  if (ajax.readyState === 4) {
    // code on completion

    ajax.onreadystatechange = CollectGarbage;
    ajax = null;
  }
};

But in Ember I don't know how to access the XMLHttpRequest object directly. The JSONApiAdapter provides with an ajax method to rewrite but I don't see how I can access the raw object:

const Adapter = DS.JSONAPIAdapter.extend({
  ajax: function(){ ... }
})




Emberjs: Setting port in FastbootAppServer script

I'm using an IISnode instance to host the Fastboot server on my Windows IIS server.

The old version of the fastboot server, Ember-fastboot-server allowed me to set a port number when running the server: http://ift.tt/2580sjR

The port needed is available at process.env.port when hosting on IISnode.

In the new FastbootAppServer, this apparently isn't possible. How would I go about setting the port number?




Accessing model properties in Controller - Ember

So, I'm trying to access my model properties in controller.

Controller:

dashobards: [
{ id: 12, name: 'test' },
{ id: 17, name: 'test2' },
];

In route I have model named dashboards

return Ember.RSVP.hash({
dashboards: this.store.findAll('dashboard'),
}).then((hash) => {
  return Ember.RSVP.hash({
    dashboards: hash.dashboards
  });
}, self);

I wanna have result in controller like this:

dashboards: [
{ id: 12, name: 'test' },
{ id: 17, name: 'test2' },
{ id: 17, name: 'test1' },
{ id: 20, name: 'test20' },
];

In controller I am trying to access this model like this:

this.dashborads = this.get(model.dashobards)

And it's not working, is there any other way of doing that?




lundi 22 mai 2017

Import elasticsearch module in Ember.js

I'm trying to import a browser build for the elasticsearch.js client. I'm using npm as my package manager as EmberJS (v2.13.1) is moving away from bower:

npm install elasticsearch-browser 

Few questions:

  1. Can I directly import the module as it is "built for the browser" and probably doesn't use any CommonJS syntax? If yes, what would the import statement look like?
  2. Am I required to use browserify to import any module I install from the npm registry? Why? How do I know which modules are browser-ready?
  3. I could install the module through bower and then do an app.import in the ember-cli-build.js file. Would that work?

As I understand, it finally comes down to using bower vs installing browserify, correct? But I still don't understand why I should have to use a transpiler.




How to setup Mandrill with Ember.js

I am just starting to learn how to work with ember.js and need a way to send emails through mandrill and mailchimp. I have setup my account with Mandrill and need a little direction on where to go from here.




How to render Ember component on same line

This Ember template code...

<div class="detail bedrooms">
  <span>Number of bedrooms:</span> 
</div>
<div class="detail temperature">
  <span>Current Temperature:</span> 
</div>

...results in this rendering... screenshot of component text on wrong line

How could one get the "25C" text to render on the same line as "Current Temperature" in the same way that "San Francisco" is on the same line as "Location"?

I have tried getting the city-temperature component to return only text, but (secondary question here) is it even possible for a component to return only text if the text is from a remote ajax request since the promise seems to need a DOM element to append to?

This Ember app is available here on GitHub. It's a modified version of the official Ember.js tutorial app with this "Current Temperature" detail added.




Ember-Bootstrap Navigation Item Float-Right

I'm currently using Ember-Bootstrap (Bootstrap 4 alpha) and would like to separate one navigation item that basically does a pull-right (was phased out with Bootstrap 4 to float-right).

A barebones Bootstrap example of what I want to accomplish:

<nav class="navbar navbar-default navbar-relative-top">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li><a>LEFT ITEM</a></li>
            <li><a>LEFT ITEM</a></li>
            <li><a>LEFT ITEM</a></li>
          </ul>

          <ul class="nav navbar-nav navbar-right">
                  <li>RIGHT SIDE ITEM</li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>

However, when I add the class float-right, navbar-right or justify-content-end to the LOG IN navigation item, there is no change in it's position of floating left by default.

I also tried using the classes to #nav.item as well as the #nav.link-to.

Float-Right will only work on the Toggle Component, but not any of the navigation items. What am I missing?

My code:


  <div class="navbar-header">
    <img class="nav-logo" src="/assets/images/nav-logo.svg" />
    <div class="float-right">
      
    </div>
  </div>
  
    
      ITEM 1
      ITEM 2
      ITEM 3

      LOG IN
    
  





Ember setupController not called on transitionTo for dynamic segment

How to get the setupController to run when transition into to a dynamic segment?

The model updates but the values initialized in the setupController are not updated because the setupController is not called.

Here is a ember-twiddle example of the setupController not being called.

http://ift.tt/2r9LUly

Any help would be greatly appreciate.




Ember combining route data

I have a situation where I have a route extending another route but will add more data to this new route. What made it tricky is we want to merge the new data with the existing base route.

I can do this syncronously in the model hook with

return Ember.merge(this._super(...arguments), {
        foo : 123
    });

But how can I retrieve data aysncrounasly and still use this Ember.merge, ie something like

model(){
  return Ember.merge(this._super(...arguments), {
            foo : 123
           baa: store.get('smthElse)
        });
}

will give me back a model with baa as a promise object, not with its resolved value.

I tried returning the Ember.merge inside of the store.get('smthElse).then but the this._super(...arguments) threw undefined errors.




how to eliminate the empty row with pop-up get closed in ember

in my hbs i have created an dynamic table. I have created an ember bootstarp modal which appears as a button click present in my hbs but without filling any details in the modal when i click anywhere on the screen modal gets closed and an empty row in created in the table. I want to eliminate that empty row. how to deal with this problem???

here is my code of the modal..

show: function() {

this.$('.modal').modal().on('hidden.bs.modal', function() {
 $('body').removeClass('modal-open');
 $('.modal-backdrop').remove();
 this.sendAction('close');
}.bind(this));  

}.on('didInsertElement')




ember firebase google login torii - help to add a custom variable

thanks for taking time to read this. I have just started using Ember and Firebase for a small private project. I am having some issues with using Google login and letting certain users have different account types than others.

What I am doing now is on a successful Google login I check for users with the same id. If it does not exist, I save the user in users with an automatically generated uid adding the desired user status, for example:

First I recover the user data from a Google login.

this.get('session').open('firebase', { provider: provider }).then((data) => {

Then if the user hasn't been saved to the database yet, I save it, with the desired custom parameter:

let newUser = this.store.createRecord('user', {
          uid: data.currentUser.uid,
          name: data.currentUser.displayName,
          email: data.currentUser.email,
          canEdit: false
        });
        newUser.save().then(() => {
            console.log('user saved');
          }).catch(error => {
            console.log('user save error', error);
          });

creating the following in firebase:

-K***********J <= create by save uid
    canEdit: false
    email: "test@test.com"
    name: "Test Test"
    uid: "9xi*************H2" <= google uid

My problem is that I am incapable of adding canEdit to the Auth object for the firebase rules nor to the currentUser that is returned by the Google login using Torii.

I do not like the idea of adding them manually later. It doesn't feel secure nor natural and it seems those changes don't bubble up to the templates to be able to use them for showing or hiding content etc.

Could someone please send me in the right direction? Any help is greatly appreciated! Please let me know if I need to explain the issue some more.

Thanks!




How to get an event.target from event on input helper in ember

iam using input helper in ember for binding attributes value

<div class="form-group profile-desa-component-form-group">
          <label class="col-sm-4 control-label"></label>
          <div class="col-sm-8 no-padding">
            
               <- this is my input helper
            
              <input readonly class="form-control btn-no-corner readonly" type="text" value=>
            
          </div>
          
        </div>

i just want to pass an event object from key-press = onKeyPressShowPanel to the controller so i can use event.target to manipulate some element via jquery snipet. this is my onKeyPressShowPanel action in controller

onKeyPressShowPanel(event){
      this.debug(event);
    },

unfortunately the event that i pass is a value that come from value = alamat. how to get an event.target from event on input helper so i can manipulate some element using jquery. Any answers would be helpfull for me.. thank you :)




Calling visit() in acceptance test Ember 2.8.0 times out

I have a simple acceptance script below which only checks for the currentURL. However whenever I run the test it only gives me timeout.

import { test } from 'qunit';
import moduleForAcceptance from 'rates-ui/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | filter panel');

test('visiting /', function(assert) {
  visit('/');
  andThen(function() {
    assert.equal(currentURL(), '/');
  });
  // assert.ok('ok', 'ok');
});




How do I connect ember app to API running on localhost:4000 virtual machine?

I tried changing the adapter host to localhost:4000, but all I see is "network error occurred" in the console.




Sending emails through ember?

This is my first post on Stack Overflow so bare with me here. I am currently working on a project using Ember.js and want to send an email with the body containing a generated code that I have built an algorithm to make. My only problem is no matter where I search I can't seem to find a solution to sending emails with Ember as it is a front end framework. Would someone mind pointing me in the right direction as to where I need to go to complete this?




Property in Ember Service undefined

I have a service for a business calendar where a property is not available to a computed property but is available in a method.

In the code below the property calendars is not defined when the computed businessYear property is accessed. On the other hand, calendars is defined when the year() method is called.

The currentYear property is used elsewhere so init() is called and the store promise is resolved before businessYear is accessed.

I've debugged this and developer tools shows that this.calenders is defined in watch variables but is still undefined in the computed property. It's almost like the computed property is being executed in another context. I'm probably missing something really basic but just don't see it.

app/services/business-calendar.js

import Ember from 'ember';
import moment from 'moment';

const { computed, inject: { service }, get, set } = Ember;

const findCalendar = (date, calendars) => {
    let p1, p13

   return calendars.find(function (item, index, enumerable) {
       p1 = moment(get(item, 'p1'));
       p13 = moment(get(item, 'p13'));
       return moment.range(p1, p13).contains(date);
   })
}

export default Ember.Service.extend({
   store: service(),
   calendars: [],

currentDate: computed(() => {
    return moment();
}),

currentYear: computed('currentDate', () => {
    return moment(get(this, 'currentDate')).year();
}),

businessYear: computed(() => {
    let calendar = findCalendar(moment(), get(this, 'calendars'));
    return get(this.calendar, 'year');
}),

init() {
    this._super(...arguments);
    get(this, 'store').findAll('calendar').then((recs) => {
        set(this, 'calendars', recs);
    })
},

year(date) {
    let d = moment(date);
      var calendar = findCalendar(d, get(this, 'calendars’));
       return get(calendar, 'year');
  }
});




Ember.js application to Firebase connection error

Hi I'm new to Ember and firebase, I'm currently going through an ember tutorial https://www.youtube.com/watch?v=-gd6LRt7Dcg and I'm unable to submit a form that connects to firebase. The error I'm recieving in my console is

_emberDebug.EmberError is not a constructor

My environment.js looks like this

contentSecurityPolicy: {
    'connect-src': "'self' http://ift.tt/1Us4oBa"
},
firebase: {
    apiKey: 'abc',
    authDomain: 'YOUR-FIREBASE-APP.firebaseapp.com',
    databaseURL: 'http://ift.tt/2qEsaVL',
    storageBucket: 'YOUR-FIREBASE-APP.appspot.com',
},

Ive also updated the permissions on my firebase:

{
 "rules": {
    ".read": "auth != null",
    ".write": true
  }
}

On my firebase console it looks like there is no connections, so I feel like there is an issue connecting my Ember application to my database.




Ember Integration Test Component Within Component

I have installed ember-bootstrap in my application. Then, I created a login-form component.

In the app/templates/components/login-form.hbs, there are 2 Bootstrap input and 1 button, which are the following:


    
        <label for="email">Email</label>
        <input id="email" value= name="email" class="form-control" oninput= type="text" placeholder="Email" required>
    
    
        <label for="password">Password</label>
        <input id="password" value= name="password" class="form-control" oninput= type="password" placeholder="Password" required>
    
    


Edited test: When I do integration test in Components, it does not seem to identify this.

test('it renders', function(assert) {
  this.render(hbs``);
  assert.equal(this.$().text().trim(), '');
  assert.equal(this.$('input').attr('name'),'email','has Email');
  assert.equal(this.$('input').attr('name'),'password','has Password');
  assert.equal(this.$('button').text(),'Login','has Login');
});

In the input, I get undefined results. What is the proper way to call input for a form.group component in Bootstrap, to be used in the component testing?

Edited: Added screenshot enter image description here




Add column to existing ember model

Wow this is hard to find.

I have an existing model in ember and I would like to add a new column. I have't been able to see how to generate this from the CLI, so have manually added it to my component.js and models/post.js. I've added the field to my form and the handlebar to my view. Checking Firebase I can confirm I'm not updating the field.

In Rails I would simply run rails generate migration add_snippet_to_posts snippet:string but doing this in Ember just creates a new model.

model/post.js

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  author: DS.attr('string'),
  createdDate: DS.attr('date'),
  text: DS.attr('string'),
  snippet: DS.attr('string') #<=manually added this.
});

component.js

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    createPost: function (model) {
      this.sendAction('createPost', model);

      // Clear each input field
      this.set('newPost.title', null);
      this.set('newPost.author', null);
      this.set('newPost.text', null);
      this.set('newPost.snippet', null); #<= manually added this
    }
  }
});

How do I do this?

Solved

Needed to update routes/index.js too:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function () {
    return this.store.findAll('post');
},
actions: {
  createPost: function (model) {
    let post = this.store.createRecord('post', {
      title: model.title,
      text: model.text,
      author: model.author,
      snippet: model.snippet, # <= add this too
      createdDate: new Date()
    });
    post.save();
  }
}

});




Ember - actions within link-to blocks

I am building a component in Ember.js which includes a table. Each tr in that table is created using so that clicking anywhere on the row will take a user to another route.

However, I'd like to make a td element in those rows clickable to open a link in a new window. I'm doing this as an action.

Right now, clicking the proper td element will both trigger the redirect and activate the action on the td element as well.

Instead, I'd like a click on the proper td element to only trigger that element's action, and ignore the event above. How would I go about doing this?

This is what my code looks like:

<table>
  
    <td>Go to link-to</td>
    <td >Send Email</td>
  
</table>




How to map model data to a chart-friendly array in ember.js

I have a model in a route that has data i'd like to chart using a chart plugin (ember-google-charts or ember-charts specifics do not matter to my issue)

in routes/server.js:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return Ember.RSVP.hash({
      stats: this.store.query('stat', {filter: {serverId: params.server_id}})
      server: this.store.findRecord('server', params.server_id),
    })
  },
  setupController(controller, models) {
    controller.setProperties(models);
  }
 }
});

My issue where/how to make stats into a proper array (using timechecked and players attributes) in order to pass the data into a charting plugin in the template.

I've tried something similar to:

stats: this.store.query('stat', {filter: {serverId: params.server_id}}).then(items => {
    //modify items here

})

but i have a hard time figuring out how to manipulate the data and build a new array without throwing errors using a forEach (which exists on the ember Array class)




createRecord with custom ID in emberjs 2.x and Firebase 3.x

Until now, I saved all my data with the following line of code:

saveUser(params) {
      let newUser = this.store.createRecord('user', params);
      newUser.save();
      this.transitionTo('index');

This worked fine, but didn't allow for custom ID's in firebase, so I changed it into:

saveUser(params) {
      let newUser = this.store.createRecord('user', {
        id: params.loginId,
        name: params.name,
        nickname: params.nickname,
        imageUrl: params.imageUrl,
        email: params.email
      });
      newUser.save();
      this.transitionTo('index');

Processes them exactly as I want them to be stored on the Firebase database, so no problem there. I'm wondering though, and not finding any solution on the web, how I can combine the two, so that I don't have to bind every param. It's bound to give problems when I add/remove model properties. Something I'm looking for would look like this (pseudo, yes I tried it, didn't work!):

let newUser = this.store.createRecord('user', {id: params.loginId}, params);

In short, I'm looking for the dynamic properties of ('model', params), but with the option to manually adjust 1 (or more) records without having to type out all of the params.

Thanks in advance !




Inject service into a Ember utility

Inject service into a utility Ember-cli ??

I have an Ember utility which makes an ajax call using Ember.$.ajax. But when I get an unauthorised response from the server I want to invalidate the session. For that, I need to access Session service which I am unable to access in utility.

In the following link, it tells how to use util inside service not service inside util http://ift.tt/2pRYxSp




Ember component multiple ajax calls

I am very new to ember js 2.13. I have a component and have defined actions in them. How do I go about making multiple ajax calls based on differing payload. Any tips or samples will be appreciated.

    for (var i = 0; i < emails.length; i++) {
  //prepare Data
   var payload = {
           "data": {
                "email": "email1",       
                   }
                }
   payLoadList.push(payload);
   }
   payLoadList.forEach(function(object){
     adapter.ajax(adapter.getFullUrl("email"), 'POST', {data: object});
   }




Where to put ajax request in Ember tutorial app?

I want to add "Weather: 24C" to the rental-listing component of the super-rentals tutorial app.

Where would be the "best-practices" place to put this ajax request?

Ember.$.getJSON(`http://ift.tt/2q0POYU}`)
    .then(function(json) {
      return JSON.parse(json).main.temp;
  });

Do I need to add a component, add a model, add a service, add a second adapter, modify the existing adapter? Something else? All of these? Is the problem that the tutorial uses Mirage? I ask this because when I think I'm getting close, I get an error like this:

Mirage: Your Ember app tried to GET
'http://ift.tt/2qvZjTP',
     but there was no route defined to handle this request.
     Define a route that matches this path in your
     mirage/config.js file. Did you forget to add your namespace?




How can I include a pure javascript file into our ember application?

Our team is working on a new website that is going to use Algolia as our search engine. The problem is that there isn't an ember module that exists to use it (they are all old or unfinished).

Therefore, in order to use Algolia, we need to include a plain javascript file into our application. What is the best way to do this? We found that it works if we include the script into our index.html.

It looks something like this

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    

    

  </head>
  <body>
    

    <!-- Include Scripts Here -->
    <script src="algolia.js"></script>


    
  </body>
</html>

We are putting a javascript file into our index.html. While this seems to work I'm a little suspicious that this is not an ember solution to the problem. Are there other ways to include external javascript files to use throughout our program? Or is this solution fine as it is?




What is the best way to share configs between backend and frontend?

I have backend built with Express.js and frontend built with Ember.js. In my git repo there are two folders with frontend and backend. I have file with constants on backend but I don't want to duplicate this file in the frontend.

Also, I could make a request from frontend to the backend to get these constants and further work with it from Ember.DS but I don't want a redundant query to API.

I think best way to make module and add it into requirements on backend and on frontend. But for this, I need to create a separate repo and I think it's overhead to use 2 repositories.

Please recommend another good way to solve this problem.




ember js, continuously invoke init method in controller when user visit page

i have a controller script in ember and iam using init() method in controller. this is my script

export default Ember.Controller.extend({
.....,
init() {
    this._super(...arguments);
    this.set('idUser', this.commonService.getUser().id);
    Ember.$(document).ready(function () {
      let height = Ember.$(window).height() - 96;
      Ember.$(".feed-activity-list").slimScroll({
        height: height.toString() + "px"
      });
    });
  },
})

the init method is invoke when user first time open the page. but when user open another page and back to this page, the controller doesnt invoke the init() method. how to force the controller run init method when user visit this page. Iam avoid using component because its hard to refactor :(




EmberJS controllers vs routes

I know this question might seem a little duplicate but the other version of this question is old and some of the content (such as Views) aren't even a part of ember anymore.

I'm about 4 weeks into my internship as a front-end developer working with EmberJS. I still don't understand when it's better to use the route over the controller or vice-versa. It seems to me that every action in the route can also be used in the controller.

The one recent thing I heard was that ember routes should be stateless where as controllers should be stateful.

What is the current state of controllers and routes. When should one be used over the other?




Is it possible to pass a function to an Ember.js component to execute it as an action callback?

I'm wondering if it's possible to pass a function as a parameter of an Ember component

// component.hbs


and then, from an action in the component, calling this same function :

// component.js
actions: {
  fun2() {
     let fun = this.get('fun');
     fun();
  }
}




Using EmberJS Helpers within SlickGrid?

I'm building a table with SlickGrid, and have tried to put in an EmberJS Helper such as to show as a value in that table (by putting that code into the formatter for the column).

But when the table gets displayed, it is displaying the EmberJS helper code, instead of it being transferred into a link as it should. I also tried putting this into an asyncPostRender for that column, but that doesn't help either.




The proper way to store/load statics in Ember App

currently I'm thinking of the way to load statics into my Ember app. The problem:

I have app branded logo, app name, app title (browser tab label), texts for routes etc. What I'm doing now is the following:

 model() {
   let defaultHeaderModel = {
   logo: '/img/logo-cloud.svg',
   brand: {
     name: 'CloudCenter',
     logo: '/img/logo-cloud.svg'
   },
   userLinks: [{
     text: 'Logout',
     route: 'logout'
   }],
   navigation: [{
     text: 'Login',
     route: 'login'
   }]
 };
}

As you can see all of the values are hardcoded. What I'd like to do is to somehow load that "statics" and use them through some variables. For ex: header.logo = resources.logo. My thoughts:

1) Use environment - store all of that values in the config.js and import it where needed. Cons: not sure if that data belongs to environment

2) ES6 POJO which can be imported to the app.

3) .json and some staticsService which will load .json file and through it I will have access to that values.

Are there any standardized approach to do such things? Or maybe better suggestions?




Background picture on EmberJS theme having troubles loading

I am using the EmberJS Start Bootstrap landing theme from emberjsthemes.com and am having some troubles playing around with it.

I am first trying to add an opacity to the background image, but keeping the text in full opacity. I've gone about it via ::before on the .intro-header css element. THe problem i am having is that the image i am searching for does not seem to be found(Looking under sources in inspector shows the img folder is not present?)

Here is an image of the sources from the browser:

Browser sources

Here is the code from my land-page.less file:

body,
html {
    width: 100%;
    height: 100%;
}

body,
h1,
h2,
h3,
h4,
h5,
h6 {
    font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif;
    font-weight: 700;
}

.topnav {
    font-size: 14px;
}

.lead {
    font-size: 18px;
    font-weight: 400;
}

.intro-header {
    padding-top: 50px; /* If you're making other pages, make sure there is 50px of padding to make sure the navbar doesn't overlap content! */
    padding-bottom: 50px;
    text-align: center;
}

.intro-header::before {
   background: url(../img/Beach.jpg) no-repeat center center;
   background-size: cover;
   opacity: .2;
}
.intro-message {
    color: #f8f8f8;
    position: relative;
    padding-top: 20%;
    padding-bottom: 20%;
}

.intro-message h1 {
    margin: 0;
    text-shadow: 2px 2px 3px rgba(0,0,0,0.6);
    font-size: 5em;
}

.intro-divider {
    width: 400px;
    border-top: 1px solid #f8f8f8;
    border-bottom: 1px solid rgba(0,0,0,0.2);
}

.intro-message > h3 {
    text-shadow: 2px 2px 3px rgba(0,0,0,0.6);
}

@media(max-width:767px) {
    .intro-message {
        padding-bottom: 15%;
    }

    .intro-message > h1 {
        font-size: 3em;
    }

    ul.intro-social-buttons > li {
        display: block;
        margin-bottom: 20px;
        padding: 0;
    }

    ul.intro-social-buttons > li:last-child {
        margin-bottom: 0;
    }

    .intro-divider {
        width: 100%;
    }
}

.network-name {
    text-transform: uppercase;
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 2px;
}

.content-section-a {
    padding: 50px 0;
    background-color: #f8f8f8;
}

.content-section-b {
    padding: 50px 0;
    border-top: 1px solid #e7e7e7;
    border-bottom: 1px solid #e7e7e7;
}

.section-heading {
    margin-bottom: 30px;
}

.section-heading-spacer {
    float: left;
    width: 200px;
    border-top: 3px solid #e7e7e7;
}

.banner {
    padding: 100px 0;
    color: #f8f8f8;
    background: url(../img/banner-bg.jpg) no-repeat center center;
    background-size: cover;
}

.banner h2 {
    margin: 0;
    text-shadow: 2px 2px 3px rgba(0,0,0,0.6);
    font-size: 3em;
}

.banner ul {
    margin-bottom: 0;
}

.banner-social-buttons {
    float: right;
    margin-top: 0;
}

@media(max-width:1199px) {
    ul.banner-social-buttons {
        float: left;
        margin-top: 15px;
    }
}

@media(max-width:767px) {
    .banner h2 {
        margin: 0;
        text-shadow: 2px 2px 3px rgba(0,0,0,0.6);
        font-size: 3em;
    }

    ul.banner-social-buttons > li {
        display: block;
        margin-bottom: 20px;
        padding: 0;
    }

    ul.banner-social-buttons > li:last-child {
        margin-bottom: 0;
    }
}

footer {
    padding: 50px 0;
    background-color: #f8f8f8;
}

p.copyright {
    margin: 15px 0 0;
}

Code from landing-header.hbs:

<!-- Header -->
<a name="about"></a>
<div class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <div class="intro-message">
                    <h1>Fairness with a cause</h1>
                    <h2>Coral Safe, Ocean Safe, Human Safe</h2>
                    <h3>25% profits donated to the <a href="http://ift.tt/22B2ofw">Coral Restoration Foundation</a> </h3>
                    <hr class="intro-divider">
                    <ul class="list-inline intro-social-buttons">
                        <li>
                            <a href="#" class="btn btn-default btn-lg"><i class="fa fa-twitter fa-fw"></i> <span class="network-name">Twitter</span></a>
                        </li>
                        <li>
                            <a href="#" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a>
                        </li>
                        <li>
                            <a href="#" class="btn btn-default btn-lg"><i class="fa fa-linkedin fa-fw"></i> <span class="network-name">Linkedin</span></a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <!-- /.container -->

</div>
<!-- /.intro-header -->

You also can see that both the /public/img folder does contain the Beach.jpg image AND the /dist/img/ folder also contains it. /dist/img folder

/public/img folder




Ember Data: Loading comments for a post from separate endpoint

I have two endpoints of interest: /posts -> to get all the posts /posts/{post_id}/comments -> to get all the comments for a post

I would like to have a comments attribute on the post model, populated with comments from the comments endpoint. How can I load comments into the posts?

I am using DS.JSONSerializer.

Thanks!




Calling feathers's services in ember js?

I have been trying to call feathers's services in ember js, but I have not found any source for my solution! I got lost, so anyone can help me please?




Ember JS performance problems

I am working on a benchmark research between change detection mechanisms in JavaScript frameworks. I am comparing Virtual DOM and KVO. For KVO example I have chosen Ember and I have developed a little demo app with a tweet list.

Referring to the dev talk 2014 here as I understand - KVO is supposed to be faster at changing one list element when there is a big amount displayed(I think even when all of the elements are changed), but for the application I have developed with these differrent implementations(React, Ember) the Ember app is significantly(alot of times) slower than the React app at changing one list item when there are 1000 displayed.

Here is a fiddle of my developed app. The tweets are sorted by favorites and they have to get sorted on every change of favorites in the model. If you take a look at the fiddle you have to press SHOW LIST for the list and buttons for changing tweets to get displayed(takes a few seconds to show up).

    App.AppModel = Ember.Object.extend({
    topTweets: function() {
        return this.get('tweets').sort(function(a, b) {
            return b.favorites - a.favorites;
        })/*.slice(0,10)*/;
    }.property('tweets.@each.favorites')
});
App.appModel = App.AppModel.create({
    tweets: renderTweets()
});

This is the model that listens to changes of favorites.

changeOneTweet:function(){
                        var iPosition = _.random(0, numTweets - 1);
                var iFavorites = _.random(0, 4000);
                App.appModel.get('tweets').set(iPosition + '.favorites', iFavorites);

                    },

This is the function that changes one "tweet".

I hope that Ember experts here can tell me what I'm doing wrong.




Ember Data: Persist fields not in model

I am developing an Ember application for an existing API. This API allows any arbitrary fields in the JSON payload, and will save all of them. When defining models in Ember I cannot anticipate all the fields that may be used. Unfortunately, any update to a model means that these fields will be lost. I'm looking for a solution that will persist fields that were retrieved by the API but not defined in the model.

Thanks.




Ember JS Call component function from the route

I have a component that has a map on it. When this map is clicked a spatial query is performed and data is returned. The data is passed up to the route via action to update the model.

At this point a user can select any of these rows and when they do I would like to be able to notify the map-component which item has been selected. Currently I get the information from when the click action occurs. Here is where I am stuck. How would I go about letting the component know that row X has been clicked from the route?

I am very new to ember (2 weeks) so feel free to correct any poor design issues as well.

    //Component (my-mapview)
    import Ember from 'ember';
    export default Ember.Component.extend({
        mapView: null,

        actions:{
            onMapviewClicked){
                let data = mapView.Query();
                this.sendAction('identified', data);
            }
        }
    });

    //Route (application.js)
    export default Ember.Route.extend({
        model: function() {
            return {            
                identifiedData:[],
            };
        },
        actions:{
           onItemsIdentified(data){
               let model = this.get('currentModel');
               Ember.set(model, 'identifiedData', data);
           }
        }
    });


    //Template application.hbs)
    
    


    //Component (my-grid)
    import Ember from 'ember';
    export default Ember.Component.extend({            
    });




Ember.js if date variable has gone over current date

I'm new to ember.js and was creating a model, with a function. The model itself will hold data on a date, but I was creating another attribute as a boolean value, if the model date has gone over the current date I want the boolean value to represent as false.

It might be easier to understand if I show you an example:

title: DS.attr('string'),
date: DS.attr('date'),
live: DS.attr('boolean', { defaultValue:function () {
    if (date)
})}

So I want Live to equal true if date is below current date, I'm not sure or would this really go in the controller, because this variable will have to be constantly checked




ember firebase google login torii - help to add a custom variable

thanks for taking time to read this. I have just started using Ember and Firebase for a small private project. I am having some issues with using Google login and letting certain users have different account types than others.

What I am doing now is on a successful Google login I check for users with the same id. If it does not exist, I save the user in users with an automatically generated uid adding the desired user status, for example:

First I recover the user data from a Google login.

this.get('session').open('firebase', { provider: provider }).then((data) => {

Then if the user hasn't been saved to the database yet, I save it, with the desired custom parameter:

let newUser = this.store.createRecord('user', {
          uid: data.currentUser.uid,
          name: data.currentUser.displayName,
          email: data.currentUser.email,
          canEdit: false
        });
        newUser.save().then(() => {
            console.log('user saved');
          }).catch(error => {
            console.log('user save error', error);
          });

creating the following in firebase:

-K***********J <= create by save uid
    canEdit: false
    email: "test@test.com"
    name: "Test Test"
    uid: "9xi*************H2" <= google uid

My problem is that I am incapable of adding canEdit to the Auth object for the firebase rules nor to the currentUser that is returned by the Google login using Torii.

I do not like the idea of adding them manually later. It doesn't feel secure nor natural and it seems those changes don't bubble up to the templates to be able to use them for showing or hiding content etc.

Could someone please send me in the right direction? Any help is greatly appreciated! Please let me know if I need to explain the issue some more.

Thanks!