dimanche 31 janvier 2016

Filtering with Slugs in Ember.js

I have two models - make and car. I have an application that shows all of the makes (manufacturers) and then another model that shows the models or cars. I have set up dynamic segment for slugs in the URL and I want to filter the makes by the slug which happens to be the niceName property.

route make.js

import Ember from 'ember';

export default Ember.Route.extend({

  model(params) {

    // find make by niceName using params.slug
    const niceName = params.slug;

    // find cars by make
    return this.store.filter('make', function(item) {
      return item.get('niceName') === niceName;
    }).then( function(result) {
      console.log( result.get('niceName')); // undefined
    });

  }

});

I have checked and it does correctly match those items with the same niceName. I can check the length and if I play with the value of niceName, it does change the length of what is returned.

The problem is that what is returned doesn't have any of the properties. If I attempt to show this in the view, it returns undefined as well.

What is filtering returning?




Process for sending ember-intl yaml files to translaor

We're just about to start using ember-intl, a wrapper for formatjs, to handle our multi-language web app. The English language file is being constructed in yaml format, though we could equally well use json. It's an implementation of the ICU Message format An example of the yaml is:

product:
  info: '{product} will cost {price, number, EUR} if ordered by {deadline, date, time}'
  title: 'Hello world!'
  html:
    info: '<strong>{product}</strong> will cost <em>{price, number, EUR}</em> if ordered by {deadline, date, time}'
blog: 
  title: 'My new blog'

Is there a canonical way of transforming this data to be handed to professional translators?

I know they use POT/PO in the GetText process, but no idea if I should be just shipping these yaml files, or doing some preprocessing first.




`SCRIPT` tags are not allowed in HTMLBars templates

Hi there and thank you for clicking my question.

I have just upgraded my application to the latest ember-cli release (2.3.0-beta.1) and now one (or more) of my templates messed with the build. What coming next seems like a trivial issue, yet I never fully got around to it very well, so I'm finally asking.

As the title suggests, I previously had <script> tags in my templates for minor things, such as a small jQuery conditional append() or anything doable by 2 or 3 lines of code. I never considered that enough motivation for creating a view, but in the meantime s**t got serious.

So, given the following snippet, what would be the recommended approach for keeping its functionality intact? Please do not mind the logic and motivation behind this specific code fragment, it's just an example:

<div class="container">
  <div class="row">
    <div class="col s12 valign-wrapper">
      <img class="materialboxed radius left" width="100" src="/default_avatar.jpg" alt="" />
      <h3>Welcome, Sarah Connor!</h3>
    </div>
  </div>
  <div class="row">
    <div class="col s12">
      {{outlet}}
    </div>
  </div>
</div>


<script type="text/javascript">
  $(document).ready(function(){
     $('.materialboxed').materialbox();
  });
</script>

Anything that won't break the existing (and anticipated?) conventions would do at this point. Thing is, I kept reading stuff on this subject but nothing had a clear stand on it, plus some quick hacks I suspect to be avoiding the conventions in use, therefore I wouldn't go for it.

I am well aware documentation is still young for anything 2.x in ember-cli and still has a long-ish road ahead. I might be able to help with it, once I figure out what to do myself.

Since this is a question that's 50/50 real issue and discussion on good practices, I'm considering posting on discuss.emberjs as well, if SO won't bring up any applicable solution / define the concepts behind in a clearer way.




Not able to get the response in my ember app for google place api

I am sending the request to google place api. I am getting an error

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I am using an api key which I created for testing purpose.I enabled google place web service api.I inserted the the url "http://localhost:4200" while generating the api.I am not sure where I am going wrong.Please suggest how should I make this correct and save the reponse.




EmberData, how do i prepend an object into the store after save, instead of appending it?

As the title say, after save a new model, how do i prepend in the store instead of appending?

Right now, creating a record will push the new object in the store, at the end of the existing objects. I need to push it at the start, how do you do that?




How can I import RethinkDB javascript library on EmberJS?

I'm trying to use RethinkDB javascript library with EmberJS. As there is no bower package for RethinkDB to install for ember, I'm trying to use npm package on ember. But I'm new to javascript as well as EmberJS I'm struggling to achieve this.

I have tried importing npm library as below but of no use.

import rethinkdb from 'npm:rethinkdb';

or on myroute.js

import rethinkdb from './node_modules/rethinkdb/rethinkdb.js';

or on ember-cli-build.js

app.import('node_modules\rethinkdb\rethinkdb.js');

nothing above worked.




How to get reference to newly created record?

I have following use case: 'I create resource 'project' in action handler in a controller, after that I'd like to make a transition to a newly created route'. My intentions looks something like this:

 createNewProject: function() {
    this.store.createRecord('project', {
      title:                    this.get('title'),
      description:              this.get('description'),
      full_description:         this.get('full_description')
    }).then((project) => {
       this.transitionToRoute('projects.show', project);
    });
  }

but it doesn't work like that because createRecord doesn't return a promise as far as I know, maybe there is some work around ?

Thank you for help.




Is there a simple command to install the hybrid app built by ember-cli-cordova on the device?

Testing a hybrid app built by ionic on Android device is very ease and fast. Simply plug the device in, and run

ionic run android

then the app can be installed on the device and you can test the app on the device.

Is there a simple command to install the hybrid app built by ember-cli-cordova on a Android device?

I use windows 10 and surface pro 3.




samedi 30 janvier 2016

How to get reference to route inside action handler?

I have a list of project and ability to delete each of them, here is my action handler for doing this:

 deleteProject: function(params) {
   this.store.findRecord('project', params).then(function(project) {
      project.deleteRecord();
      project.save();
      // this.transitionTo('projects');
    });
 }

What I want to do is to redirect back to route where list of project is displayed. As you can see I've tried to do this using this.transitionTo('projects'), but it doesn't work because this does not point to route anymore inside handler.

How to get reference to this route where this handler is declared in order to make transition to another route?

I'm using Ember v. 1.13




this.get('x') returns ' undefined' instead of 'undefined'

In a form-component I have an observer that tests if a property is valid before to start further validations.
So I checked if the property has not yet been defined (happens at initialization f.e.)

if(typeof this.get('myProperty') !== 'undefined') { 
    //do smth 
}

Then I realized that this.get would not return a type of 'undefined' but a string with the value undefined.
Fair enough.

BUT

console.log(this.get('myProperty'));

gives me ' undefined' instead of 'undefined' - notice the space before 'undefined'!

Is this a bug?
Or do I really have to check for ' undefined' with a space and is there a reason for that?

Ember-cli: 1.13.7
Ember: 2.0.1




Is it possible to extract html from ember templates using ajax

I have a simple ember application. The application file structure is as follows (I will only show the relevant ones),

app/
-> components  //subdirectory of app/
-> controllers
-> routes
-> templates
index.html     // auto generated file
.
.
.

under my templates directory I have two files application.hbs and page1.hbs

// app/templates/application.hbs
<body>
    <h2 id="title">Welcome to Ember</h2>
    <button onClick={{action 'ajaxCall'}}>Press Me</button>
</body>

// app/templates/page1.hbs
<body>
    <h2 id="title">Welcome to Ember</h2>
    <button onClick={{action 'ajaxCall'}}>Press Me</button>
</body>

So, when a user clicks a button the 'ajaxCall' action is executed

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

export default Ember.Controller.extend({
    actions: {
        ajaxCall: function() {
            console.log("this is from ajaxCall function");

            Ember.$.ajax({
                url: "http://localhost:4200/page1",
                dataType: 'text',
                success: function(data) {
                    console.log("Extracted HTML SUCCESSFULLY");
                    console.log(data);
                }
            });
        }
    }
});

The ajax call appears to work, but instead of returning the html from page1.hbs (which is what I want), it returns the html from index.html. Is what I am trying to do here able to be accomplished? Any tips would help, thank you in advance. My goal is to build a single page application, without redirecting to a new page, instead load the html as needed.




Who and how should use a global service in response to a GUI event

There are many client-side frameworks which encourage the developer to split the GUI into a tree of components. In this question I do not assume any particular framework, or even language, but rather seek for lessons learned from all the diverse frameworks like React, Vue, Ember, Aurelia, or Windows Forms or XAML, that could be useful for someone who'd like to maintain a single page app in Backbone.js.

To make the question concrete, let's think about something like facebook's main page. I have one component (ListOfPostsComponent) which displays a list of posts, where each post is actually displayed by a child component (PostComponent) which in turn might have some component for displaying comments (ListOfCommentsComponent) in which there are multiple instances of CommentComponent, and an instance of AddCommentComponent which lets the user add a comment if she types in text into NewCommentTextComponent and presses the AddCommentButtonComponent.

The goal is to POST a request trough API, on success add the comment to the list of comments, and update the number of comments displayed in the post summary. Realistic enough?

Now, it seems obvious that the click into the button triggers some chain of events starting in AddCommentButtonComponent. What follows is the interesting part. I see several different ways to approach the two problems:

Problem 1. which component should take action of initiating the POST Problem 2. how exactly it should initiate it

Here are several ideas I considered, but I invite you to propose others:

For problem 1:

Option A) (silly) the AddCommentButtonComponent is in charge of adding the comment, so it performs the request. This option requires the button to know the content of the NewCommentTextComponent and that it will inform somehow it's parents about the success of the operation. Seems like too much coupling.

Option B) the AddCommentComponent which knows about both NewCommentTextComponent content and listens to AddCommentButtonComponent 'click' event performs the request. It requires at the minimum a contract which specifies how the text content is being exposed from NewCommentTextComponent, how to listen for events and what is the event name, but it seems to be a right level of coupling, and/or reason for existence of the AddCommentComponent in the first place. We still need to fire some event to inform parents that a new comment is available.

Option C) there is some global events bus/hub, and the communication between components goes by passing one-way events, probably namespaced somehow to avoid collisions. AddCommentButtonComponent sends a 'click' event to a channel/namespace for which the AddCommentComponent listens/subscribes, which in turn emits event 'i-am-about-to-create-a-comment-please-send-me-data', for which NewCommentTextComponent responds with something, etc. Seems like a total mess. Let's call it Erlang style?

Option D) the event is propagated upwards until some authority is sure that noone above it knows what to do with it. In our example the PostComponent decides that it is the last outpost on the border between interested and not interested controls. PostComponent is interested in the event because it wants to update the comments count, and ListOfPostComponents is not interested, so we have to handle it here. This solution seems to asssume a lot of knowledge about the context: PostComponent must know who is the parent and what is it interested in, and so does AddCommentComponent.

Option E) (let's call it the HTML way) the (properly namespaced) event bubbles up to the root accumulating any additional pieces of information as it goes up. For example the AddCommentButtonComponent emits just a simple 'click', but the AddCommentComponent adds a new field with text content to it (and changes name of the event to 'add-comment'), then PostComponent decides to initiate the request but it does not stop event bubling, but might enhance the event with additional name/properties. The problem with this is that it does not answer the question: who should perform the request.

Option F) similar to Option E) but request is issued by some separate service which simply listens to events at the root.

For problem 2:

Option A) (silly) the control simply uses $.ajax.

Option B) (global app) the control uses app.api.addComment(post,text,callbacks)

Option C) (deps injection) the control uses this.api.addComment(post,text,callbacks) where the this.api is initialized in constructor and passed from the parent. The problem with this is that now the parent has to know about all the dependencies of children, and grand children etc.

Option D) (dependency injector) the control uses this.api.addComment(post,text,callbacks) where the this.api is magically initialized during construction by some dependency injector which knows what the control needs

Option E) (service locator) the control uses something like serviceLocator.getApi().addComment(post,text,callbacks).. which is really just app.api.addComment(post,text,callbacks) in disguise ?

Option F) (my interpretation of react) the control expresses intent of adding a post, but does not pass any callbacks or otherwise expect the answer. Someone delivers this intent to a service which can process it. Later when the answer comes it is pushed top-down from the root to all nodes of the tree of components (which allows for a parent to selectively filter information passed to children). Alternatively the response is passed to all components directly. This seems to me quite similar to ...

Option G) (events bus) the control emits an event that it wants a POST to be performed. A service listens to such events and performs the POST, and when it is done it triggers an event containing the answer. All components interested in answer simply subscribe to this global event.




Why is this Route's model updated in only 2 of 3 cases? - Ember.js 2.3

I'm using Ember.js 2.3. I have a parent Route that looks like this:

App.AppRoute = Ember.Route.extend
  model: ->
    Ember.RSVP.hash
      projects: @store.findAll "project"
      clients: @store.findAll "client"
      consultants: @store.findAll "consultant"
      practiceAreas: @store.findAll("practice_area").then (practice_areas) ->
        practice_areas.sortBy "displayName"

I have a child Route looking like:

App.AppProjectRoute = Ember.Route.extend
  model: (params) ->
    hash = @modelFor "app"
    hash["project"] = @store.findRecord "project", params.project_id
      .then (p) -> p
    hash["workWeeks"] = @store.query "work-week", project_id: params.project_id
      .then (weeks) -> weeks
    console.log _.keys hash
    Ember.RSVP.hash hash

The template for the child Route contains:

  <hr/>
  {{add-consultant project=model.project consultants=model.consultants addConsultant="didAddConsultant"}}
</div>

Then the add-consultant component contains a computed property:

remainingConsultants: Ember.computed "project", "project.consultants.[]", "consultants.[]", ->
  already_involved = @get "project.consultants"
  remaining        = @get "consultants"

  already_involved.forEach (ai) ->
    remaining = remaining.reject (r) -> r.get("id") is ai.get("id")

  remaining.sortBy "displayName"


Case 1

When I navigate directly to a project, such as http://localhost/#/app/project/27, the Routes model hook correctly queries the server for data and renders the template and components.

Case 2

When I navigate directly to a project, then manually change the project ID in the URL (say from http://localhost/#/app/project/27 to http://localhost/#/app/project/28 and press Enter, the Route model hooks update, and the template and components are correctly rerendered.

Case 3

However - and this is my confusion - navigating to a project by clicking a link (say, from a list of Projects using the {#link-to} helper) - even if I first visit the page sucessfully as in Case 1 or Case 2 and then immediately navigate back to the same Project, I get an error:

TypeError: already_involved is undefined

Looking deeper, it turns out that @get "project" itself is undefined.

What is different about using {#link-to} over "direct" navigation that causes this? Is it an error I made in defining my Route model heirarchy? Am I missing some kind of event hook?




Rendering templates from nested routes in Ember JS

I'm trying to render a template from a nested route using an {{outlet}} tag. I can't seem to think of what I may be doing wrong.

Router.js

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

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

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

export default Router;

support.hbs

<div class="container mtx pbxl of-auto">
  <div class="col-s-3">
    <ul class="list pan mtn">
      <li class="db mbs f5">{{#link-to 'support' class="light-blue link"}}Terms of Service{{/link-to}}</li>
      <li class="db mbs f5 light-blue">Upcoming Features</li>
      <li class="db mbs f5 light-blue">Contact Us</li>
      <li class="db mbs f5 light-blue">Support</li>
    </ul>
  </div>
  <div class="col-s-7">
    {{outlet}}
  </div>
</div>

terms.hbs

<div class="db light-blue lh-copy">
Donec at orci vel erat lobortis mollis. Sed et velit leo. In rutrum dictum elit in venenatis. Aenean suscipit ut ex non luctus. Integer feugiat purus quis nibh egestas tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In hac habitasse platea dictumst.
</div>

These are the 3 pieces of the puzzle as far as I know. The support.hbs template is rendering fine, but the outlet is not renderings the terms.hbs template.

Any idea what I might be doing wrong?




How to unload a record in Ember 2.3.0?

I am upgrading an Ember 1.13.0 application to Ember 2.3.0 and I'm facing a little issue where I am unable to unload a record from the Data Store without causing Ember to make a HTTP request. I do not want to delete the record in the server. I simply want to remove it from Ember Data Store.

I was using the following Ember DS.Store API: http://ift.tt/1slRQha in Ember 1.13.0 and it worked fine. Sample:

this.store.find('post', 1).then(function(post) {
  this.store.unloadRecord(post);
});

After upgrading to 2.3.0, when I monitor the network tab in Chrome, Ember is making a GET request to find the record and then unload it. Because it fails to find (our server does not have an API to match this call), it doesn't unload the record and the changes don't appear in the UI.

I tried to fix this by instead doing something like:

this.store.peekAll('posts').findBy('id', 1).then(function(post) {
    this.store.unloadRecord(post);
});

but this doesn't seem to work. What is the right way to unload a record from Ember Data without making HTTP calls? Thanks.




how to clear input helper after action is handled?

I'm using Ember v 1.13.8

I have input helper:

{{input type="text" value=newData action="addNewItem"}}

and action handler:

actions: {
    addNewItem: function(value) {
      this.get('personList').pushObject({name: value});
      this.set('newData', '');
    }
}

As you can see in order to clear input I have variable in controller where I store temporary value. I made input helper dependent on it and this approach works, but I wonder may be there is Ember way of doing this?




vendredi 29 janvier 2016

My app cannot work when I installed ember-cli-cordova, I need some advises

I installed ember-cli-cordova following ember-cli-cordova's Getting Started guidance.

Step 01:

npm install -g ember-cli

npm install -g cordova

Step 02:

ember new project-name

Step 03: You have to run ember commands in the project directory.

cd project-name

Step 04: Create "dist" directory.

ember build

Step 05:

ember install ember-cli-cordova

Step 06: edit config/environment.js

1) change "locationType: 'auto'" to "locationType: 'hash'". (cordova needs hash as locationType)

2) Add setting "Env.cordova...."

Step 07:

ember generate cordova-init com.rabit.hybrid

Step 08: Edit config/environment.js

defaultLocationType: 'hash',
...
cordova: {
...
    platform: 'android',

Step 09:

ember generate cordova-starter-kit

Step 10:

C:\MyWorkSpace\Dvlp\Trial\hybridOne>ember server

version: 1.13.13

Livereload server on http://localhost:49152

Serving on http://localhost:4200/

ENOENT: no such file or directory, stat 'C:\MyWorkSpace\Dvlp\Trial\hybridOne\tmp\concat_with_maps-input_base_path-EtFoLMHC.tmp\0\bower_components\hammerjs\hammer.js'

Error: ENOENT: no such file or directory, stat 'C:\MyWorkSpace\Dvlp\Trial\hybridOne\tmp\concat_with_maps-input_base_path-EtFoLMHC.tmp\0\bower_components\hammerjs\hammer.js'

at Error (native)

at Object.fs.statSync (fs.js:892:18)

at ConcatWithMaps.keyForFile (C:\MyWorkSpace\Dvlp\Trial\hybridOne\node_modules\ember-cli\node_modules\broccoli-sourcemap-concat\node_modules\broccoli-caching-writer\index.js:90:20)

Hope someone can tell me what's wrong.

Thanks in advance!




Save multiple model at once, in bulk

I know this subject has already been discussed around stackoverflow and other forums, but I cannot find the right way to do it.

I have a model called "post" which contain post information (user, description, etc...). The user receive a few post, reads them and make actions on them. The posts are coming from my api when I request a GET /api/posts/

I also have a model called "post-state" where I save the action of people reading the post: when they like, share, vote, or favourite the post.

export default DS.Model.extend({
    post: belongsTo('post'),
    user: belongsTo('user'),
    liked: attr('boolean', { defaultValue: false }),
    favourited: attr('boolean', { defaultValue: false }),
    voted: attr('boolean', { defaultValue: false }),
    shared: attr('boolean', { defaultValue: false }),
});

I'm looking for a way for my ember application to save my post-state models in a bulk, just the way I received the post in a bulk as well. The post states would be saved with an api call POST /api/post-states/

I've read in a discussion that the best way would be to create a custom adapter, but I'm not sure what to put in it to be able to do that... maybe to create a function saveAllRecords()?

What would be the best solution for me?

Thank you for you help!




How to track down Uglify error with Ember CLI

When I build my Ember CLI app in development, it works fine. When I try to build it for production, Uglify gets upset:

$ ember build --environment=production
version: 1.13.15
Build failed.
File: assets/vendor.js (70503:3)
Unexpected token name «use», expected punc «,»
Error
    at new JS_Parse_Error (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:1508:18)
    at js_error (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:1516:11)
    at croak (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2008:9)
    at token_error (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2016:9)
    at expect_token (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2029:9)
    at expect (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2032:36)
    at expr_list (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2535:44)
    at subscripts (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2674:30)
    at subscripts (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2651:20)
    at expr_atom (eval at <anonymous> (/Users/michael/Code/queue/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:24:4), <anonymous>:2527:20)

I'm at a loss for what this error means - Unexpected token name «use», expected punc «,» - and assets/vendor.js (70503:3) isn't a file I can find anywhere.

If anybody can give me a suggestion of how to track down this error, I'd be really grateful!




Localstorage service is not notifying of property changes

I have a local storage service I've created which looks like this

import Ember from 'ember';
import ENV from 'bidr/config/environment';

const stringify = JSON.stringify;
const parse = JSON.parse;

function setItem(key, value) {
  localStorage.setItem(key, stringify(value));
}

function getItem(key) {
  var result = localStorage.getItem(key);
  if (result) {
    return parse(result);
  }
}


export default Ember.Service.extend({
  namespace: ENV.APP.LocalStorageKey,
  user: null,

  init: function() {
    this.set('user',this.getItem('user'));
  },

  setItem: function (key, object) {
    var ttlOptions = arguments[2];

    if (ttlOptions) {
      this._setTTLKey(key, ttlOptions);
    }
    this.set(key,object);
    setItem(this._namespacedKey(key), object);
  },
  getItem: function (key) {
    return getItem(this._namespacedKey(key));
  },
  keyExpired: function (key, now) {
    var ttl = this.getItem(`_ttl_${key}`);
    if (ttl) {
      var expiry = new Date(ttl.lastUpdated)
          .setTime(new Date(ttl.lastUpdated)
          .getTime() + ttl.ttl);

      now = now || new Date();

      return now > expiry;
    }
    return true;
  },
  _setTTLKey: function (key, ttlOptions) {
    var dateTime = new Date();
    setItem(this._namespacedKey(`_ttl_${key}`),
      {ttl: ttlOptions.ttl, lastUpdated: dateTime}
    );
  },
  _namespacedKey: function (key) {
    return this.get('namespace') + `.${key}`;
  }
});

The user object is so I can access it directly in a template or as a computed property value.

The problem is another computed property that depends on a property of user in the service is not being notified when it gets changed. In my application controller I have an action that updates a property on the user property in the service

updateActiveEvent(eventInfo) {
    var currentUserInfo = this.get('localStorage').getItem('user');
    currentUserInfo.active_auction = eventInfo.eid;
    this.get('localStorage').setItem('user',currentUserInfo);
},

(this comes in from a socket service) this is working properly as after this action fires I can check the browsers localstorage object and see the active_auction property of it has changed. But in my template where I am displaying that (or a computed property based on that) it's not updating.

I saw there is possibly a way I can force ember to notify of property changes but couldn't seem to get this to work, not sure if I was doing it right.




Component resets all attributes when a dynamic attribute is changed

I have a component that I pass some static and dynamic parameters. The component updates these static values during interaction. When dynamic parameters are updated by the implementing component, all the static parameters are reset. I would expect that the component retains the updated value.

Ember Twiddle

I have implemented a work around where those values are set only during init, but I am wondering if this is intended behaviour.




Binding to a model relationship property fails in the each helper

Binding to a model relationship property fails in the each helper as demonstrated below:

Here are my models:

`//app/models/category.js
export default DS.Model.extend({
  name: DS.attr(),
  image: DS.belongsTo('image', { async: true }),
});

//app/models/image.js
export default DS.Model.extend({
  name: DS.attr('string'),
  thumbfullfilepath: DS.attr('string'),
  category: DS.belongsTo('category', { async: true })
});`

When I run the category model in the each handlebars helper below to retrieve the 'thumbfullfilepath' for an image tag, no value is bound to the img src:

`{{#each model as |category|}} 
    <div class="small-element item">
        <div class="cat-name"><a href="#">{{category.name}}</a></div>
        <div class="cat-name edit">{{#link-to 'admin.categories.edit' category}}Edit{{/link-to}}</div>
        <span class="entry-thumb">
            <img src={{category.image.thumbfullfilepath}} alt="">
        </span>   
    </div>
{{/each}}`

However, I have verified the relationship binding works on display of a single model as when I visit the "admin.categories.edit" route which loads a single category model, the {{category.image.thumbfullfilepath}} path is retrieved and reflected in the template. This has led me to believe that for some reason, model relationship bindings fail in the each handlebars helper within templates.

Would someone shed some light here.

## The solution that has worked for me

I created an image component "image-atom" whose component.js is as below:

`//pods/components/image-atom.js
export default Ember.Component.extend({
  tagName: 'img',
  attributeBindings: ['src', 'alt'],
  alt: '',
  src: Ember.computed(function () {
    this.get('source').then((image) => {
        this.set('src', image.get('thumbfullfilepath'));
    });
    return null;
  })
});`

Which I use like so here below and it works but it feels hacky:

`{{#each model as |category|}} 
    <div class="small-element item">
        <div class="cat-name"><a href="#">{{category.name}}</a></div>
        <span class="entry-thumb">
          {{image-atom source=category.image alt=""}}
        </span>   
    </div>
{{/each}}`

Here below are the environment details:

(a). ember cli version: "2.2.0-beta.2" (b). ember-data: "^2.2.1" (c). ember: "2.2.0" (d). node: "0.12.7" (e). npm: "2.14.10" (f). os: "darwin x64 El Capitan"

Let me know.




Ember CLI livereload does not detect changes

Livereload

I'm having problems getting Ember CLI (1.13.15) to detect changes. When I create a new application with

ember init

And run the development server with

ember serve

The project compiles and I see the page. When I change something, the server detects changes in the console, but nothing happens even if I refresh page. The changes become visible only after I rerun the ember serve

Slow compile

Also on an empty app it takes 30 sec to compile app on Samsung 850 Pro SSD & i7 2600k with admin rights and after ember-cli-windows run.

Versions

  • Windows 10 with all the updates
  • ember-cli: 1.13.15
  • node: 4.2.6
  • npm: 2.14.10



Can an ember(-cli) app trigger window.onerror?

Is there any kind of javascript error that is not handled by onerror in an ember(-cli) application? In other terms, is there any need to add a handler to window.onerror?

In my tests I could not come up with any error that would no be handled by Ember's onerror. Syntax errors didn't get past ember-cli's build process.




Bootstrap Div .container doesn't centered in EmberJS app

I want to build responsive application by using Twitter Bootstrap. I found many ways how to import this, but they all have the same result. Tag div with class .container doesn't auto centered (horizontal), it shows on the left side of the page. In Chrome DevTools panel .container doesn't have any width calculations for responsive design. And .conatiner doesn't have margin-left, margin-right: auto. I don't know why it's not working properly. I was trying many guides. For example this one: http://ift.tt/20xhvGi The last commands that I used to import Bootstrap was:

ember install ember-cli-sass
ember install ember-sass-bootstrap

Here is my simple project: http://ift.tt/1RQGVNq

And html template application.hbs:

<div class="contatiner">
  <div class="row">
    <h1>Reading List</h1>
    {{outlet}}
  </div>
</div>

I haven't any expirence in EmberJS. It's my first example application. But I spent a lot of time to resolve this simple problem and it makes me mad. Bootstrap works excellent in all of my Ruby on Rails applications.




Parameter passed to Handlebars helper appears as the key instead of the value

I'm making an Ember.js application, and using Handlebars for templates. I've created a handlebars helpers which currently looks like this:

Ember.Handlebars.registerHelper('beautify', function(string) {
    var str= new Ember.Handlebars.SafeString(string.replace(/_/g, ' '));
    return str;
});

And call it like so:

        <td class="small-cell">{{beautify foo}}</td>

But instead of passing the variable "foo" to the helper, handlebars instead passes the string "foo". This is especially odd, because if I try logging the variable with the helper

{{log foo}}

The correct string is displayed.




Embedded model does not display from cache

When trying to load embedded data, I have a problem in that when the model is already cached on my page, this embedded data will not load in the view. If, however, it it is reloaded from scratch and therefore read from the API, it does load. I can see that the data is being loaded into the model from the Ember inspector plugin, however. If you could tell me the issue here so that the data will load every time, this would be appreciated. Many thanks.

import DS from 'ember-data';
import WebApiSerializer from 'ember-web-api/serializers/web-api';

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

Models

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    graduationDate: DS.attr('string'),
    institutionLevel : DS.attr('string'),
    subjects: DS.hasMany('subject'),
    cv: DS.belongsTo('cv')
});

import DS from 'ember-data';

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




How can I use RethinkDB with EmberJS framework?

I'm new to EmberJS and RethinkDB. I'm using changefeeds of rethinkDB for user specific data to create web push notification application with emberjs.

I have created the same with nodejs and socket.io. it is working fine. I want to convert it to emberjs code. But when i tried to include rethinkdb in bower.json. Im getting a message "Package RethinkDB not found".

"rethinkdb": "~2.0.0"

enter image description here

The below is my working code for Nodejs with Socket.io and RethinkDB

server.js

var sockio = require("socket.io");
var app = require("express")();
var r = require("rethinkdb");
var http = require('http');

var io = sockio.listen(app.listen(3000), {log: false});

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/home.html');
});



r.connect({host: 'localhost', port: 28015})
.then(function(conn){return r.db('my_db').table('user_feeds').changes().run(conn);})
.then(function(cursor){cursor.each(function(err, data) {         
    io.emit('feeds', data);  
    console.log("after Data >>>>>\n"+JSON.stringify(data));
});});

console.log("server started @ http://127.0.0.1:3000/");

home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Asset Tracker</title>
<script src="http://ift.tt/1Pmz4oM"></script>
<script type="text/javascript">
window.onload = function() {
var socket = io.connect();
socket.on("feeds", function(data) {  
  document.getElementById("feeds").innerHTML = JSON.stringify(data);

});
};
</script>
</head>
<body>
<div id="feeds"></div>
</body>
</html>

I want the above code to be migrated to emberJS. As I'am new to ember I find it difficult to migrate. Not much of a code sample available for rethinkdb with emberjs online.




jeudi 28 janvier 2016

Ember: Set default value to bs-form-element

How to set the default value of {{bs-form-element controlType="date" property="model.orderDate"}} I am unable to bind it properly.




Set default (selected) option Ember 1.13.11

Sort version:

Why does this work: <option disabled={{option.isSelected}}>

But not this: <option selected={{option.isSelected}}>

Long version:

This is more about me learning how Ember works than about getting this working, since there are lots of working examples for this already.

I'm trying to set the default selected option in a select menu. It looks like there are different ways of doing this and that the recommended method is changing.

I'm working in Ember 1.13.11 but want to be Ember 2.0 compatible.

I haven't found a Ember 2.0 compatible method that didn't involve a template helper for the selected attribute. I can create a true/false value as a property on the controller. I know I'm doing it right because disabled works properly. Why does this fail only for select?

Template call:

{{version-details item=version status=version.status}}

Component controller:

import Ember from 'ember';

export default Ember.Component.extend({
  tagName: 'select',
  options: Ember.computed('status', function() {
    var statusOptions = ['beta', 'current', 'future', 'retired-beta', 'retired', 'unknown'];
    var selected = this.get('status');
    var optionsData = [];
    statusOptions.forEach( function(status){
      var isSelected = (selected == status);
      optionsData.push({ status: status, isSelected: isSelected });
    })
    return optionsData;
  }),
  setAction: '',
});

Component:

{{#each options as |option|}}
  <option selected={{option.isSelected}}>{{option.status}}</option>
{{/each}}




Ember 2.0 alternative for transitionTo since its deprecated

So I am trying to make a component named 'fsol-app-btn' that is an A tag link. First thing I did was change the tagName in the component.js So it properly renders on the page as an A tag.

Here is the component.js:export default Ember.Component.extend({ classNames: ['btn', 'btn-app'], tagName: 'a', num: false, color: 'aqua', route: 'dashboard', mouseDown: function() { console.log('f'+this.get('route')); //this.transtionTo(this.get('route')); this.sendAction('action', this.get('route')); } }); Here is the component's template.hbs: {{#if num}} <span class="badge bg-{{color}}">{{num}}</span> {{/if}} <i class="fa fa-{{icon}}"></i>{{title}}

Now here it is in the html:{{fsol-app-btn icon='bullhorn' title='Notifications' route='index' num='3' color='yellow'}}

icon, title, color, and num all work and are just for styling so this one component can be used for any kind of button I want.

But the button's main functionality is to click and do something, in this case I want it to go to a route, such as a link-to helper would. I tried passing a route='name of route' and then on mouseDown call this.transtionTo(this.get('route'));

But I get a deprecated warning and it doesnt work.

So how do i do this? btw: I also tried this.sendAction() and in this case I had an action called 'clicked' defined like so: {{fsol-app-btn icon='bullhorn' action="clicked" title='Notifications' route='index' num='3' color='yellow'}}

But then I got an error saying that my fsol-app-btn's parent component had no action handler for: clicked

I tried making routes all over the place in locations I thought would catch the action but to no avail.

Any ideas?




Scoping emberjs query params to the controller

I have a route in ember defined as such:

this.route('products', { path: '/t' }, function() {
  this.route('index', { path: '/:taxon' });
});

So I am able to visit the following URLs:

  • /t/shirts
  • /t/shoes
  • /t/etc...

each of these may have a series of query parameters also. For example I could make a request for red shirts like this /t/shirts?colour=red. This is great but I want to persist the query parameters across the controller instance instead of the model. So if I was searching for red shirts and then transitioned to looking at shoes (via a {{#link-to}}) then the query parameters would be available on that route too i.e. /t/shoes?colour=red. Currently I don't seem to be able to do this.

I found a reference to something in the ember documentation that states I can set showMagnifyingGlass's scope to "controller" and this will do what I intend but it does not seem to be working. Have I got the wrong end of the stick with showMagnifyingGlass? I believe the point of this is scope the query parameters to the controller instance and not the model so that if I were to click on a link that changes the routes model it does not affect the query params.

This is what I have included in my controller:

queryParams: [{
  showMagnifyingGlass: {
    scope: 'controller' // Scope the parameters to the controller so transitions share state.
  }
}]




Firefox/Firebug not showing thrown error messages

I had an error in my code which caused an exception to be thrown. It did originate from creating an Error() object, but it was from EmberError.

Firefox and Firebug produce the same output: enter image description here

While Chrome actually shows the thrown message: enter image description here




How to get subdomainName in Ember-cli (2.3)

I have an ember-cli project using ember2.3 that is proxying to a server api. Right now, for my development environment, for example, I use this to proxy to the node server at :3000.

ember serve --proxy http://localhost:3000/

Part of my server side code needs the subdomain of the url to fetch data. Before, in Ember1.7, because I was not using ember-cli and not proxying, the subdomainName could be gotten via req.subdomains. But now, i need to make sure that the subdomain is being sent in the request's headers via the RESTAdapter.

Therefore, I need a way to get the current url and subsequently the subdomain of the url that the application is at.

For example, if I were current at the path:

http://ift.tt/1PlB3K6

I would need to parse out "dev" and send it in the request headers. How would I get that subdomain and/or the url.




Data not loading in API but is in Cache - Ember

When trying to load embedded data, I have a problem in that when the model is already cached on my page, this embedded data will not load in the view. If, however, it it is reloaded from scratch and therefore read from the API, it does load. I can see that the data is being loaded into the model from the Ember inspector plugin, however. If anyone could tell me the issue here so that the data will load every time, this would be appreciated. Many thanks.

import DS from 'ember-data';
import WebApiSerializer from 'ember-web-api/serializers/web-api';

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

Education Models

import DS from 'ember-data';

    export default DS.Model.extend({
        name: DS.attr('string'),
        graduationDate: DS.attr('string'),
        institutionLevel : DS.attr('string'),
        subjects: DS.hasMany('subject'),
        cv: DS.belongsTo('cv')
    });

Subject Model (Embedded to Education)

import DS from 'ember-data';

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




Ember retry transition from a failed promise with new query params

I have a route called estates where users will see a list of estates they own and from which they can view the details of one estate.

In order to enter the estate route, I must pass an estate_id and a mode parameter. The mode is, by default, set to open

model(params) {
  return this.store.queryRecord('estate', params);
},

In some cases can return an error asking for a different mode. In that situation, the users will be prompted to choose either between "backup" or "saved" via a popup, since it must be a user's made decision. I tried the following expecting the queryParamsDidChange hook to retry the transition but it did not work since Ember has not entered yet the estate route. So how can I could I retry a transition that never resolved with modified query params?

Estate model extract:

queryParams: {
  mode: {
    refreshModel: true,
    replace: true
  }
},


actions: {
  error(reason, transition) {
    // 1. Abort the transition so that we don't default to the error page.
    transition.abort();

    // 2. Set controller's previousTransition property so that we can retry it.
    this.controllerFor('estate').set('previousTransiton', transition);

    // 3. Parse the error
    const promiseErrors = reason.errors;

    for (let e=0; e<promiseErrors.length; e++) {
      switch(promiseErrors[e].reason) {
        case 'backupOrSaved':
          this.send('showErrorOnEstateOpen');
          return;
      }
    }
  },
},

Estate controller extract:

queryParams: ['mode'],
mode: 'open',

eventBusService: Ember.inject.service('event-bus'),

_listen: function() {
  this.get('eventBusService').on('alterEstateOpenMode', this,   '_alterOpenMode');
}.on('init'),

_alterOpenMode(mod) {
  this.set('mode', mod.mode);
},




Ember 2 set select value in component

I have a little problem.

There is some component, which must render the form for editing model's record. And I need render it on listing page below each model's record.

There is a gist: http://ift.tt/1ZVHzIQ

Problem: When I open it, all fields without select-tags are filled. If render e.g. groupId or another SELECT-tag's value as label it shows right (e.g. '6'). But select-tag doesn't show selected value, and all select-tags shows only prompt.

How can I redraw or refill select-tags? Maybe I did smth wrong?




testing application and software using metrices

I just came across this paper suggesting that best way to evaluate the framework of application is by Quality Tests consisting of:

Size Metrics:

  • Lines of code (LOC).
  • Bumber of statements.
  • The comment lines and the ratio between comment lines and lines of code.

Complexity Metrics:

  • McCabe’s cyclomatic complexity(CC),
  • Branches and Depth.

Maintainability Metrics:

  • Halstead metrics (Program Volume and Program Level) and Maintainability Index

Validation Tests

  • Yasca (http://ift.tt/20uGkmb) software utility.
  • In combination with JavaScript Lint (javascriptlint.com).
  • For Overall errors include critical, high, low severity errors and informational errors.

There is no proper explaination why this test are best I wanted to take it as my research topic for master but wanted a second suggestion ..




Can't find variable: exports with Karma with Ember-Cli

I'm trying to run my tests with Karma in an Ember app.

I have this karma.conf.js file :

// Karma configuration
// Generated on Wed Jan 27 2016 13:35:28 GMT+0000 (UTC)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: http://ift.tt/1ft83uu
    frameworks: ['mocha'],


    // list of files / patterns to load in the browser
    files: [
      'bower_components/jquery/dist/jquery.js',
      'bower_components/ember/ember.debug.js',
      'bower_components/ember-data/ember-data.js',
      'bower_components/ember-mocha-adapter/adapter.js',
      "app/**/*.hbs",
      "app/**/*.js",
      "tests/**/*.js"
    ],


    // list of files to exclude
    exclude: [
    ],

    plugins: [
     'karma-mocha',
     'karma-ember-preprocessor',
     'karma-phantomjs-launcher',
     'karma-babel-preprocessor'
    ],



    // preprocess matching files before serving them to the browser
    // available preprocessors: http://ift.tt/1gyw6MG
    preprocessors: {
      'app/**/*.js': ['babel'],
      'tests/**/*.js': ['babel']
    },

    babelPreprocessor: {
      options: {
        presets: ['es2015'],
        sourceMap: 'inline'
      },
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: http://ift.tt/1ft83KQ
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,


    // start these browsers
    // available browser launchers: http://ift.tt/1ft83KU
    browsers: ['PhantomJS', 'Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

When I do karma start and karma run, I have this error message :

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  ReferenceError: Can't find variable: exports
  at /frontend/app/adapters/application.js:3

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  ReferenceError: Can't find variable: exports
  at /frontend/app/adapters/application.js:3

Here is the line in question :

export default ActiveModelAdapter.extend(DataAdapterMixin, {

I already saw this question on the subject but I think there must be a better way with a preprocessor.

If I understand, babel should convert, from es6 to e5, this file but it didn't.

I didn't found a tutorial to setup ember tests with ember-cli + karma + mocha. Any resource is welcomed.




Use Onload on image tag in ember

I have a template in which photos are being displayed in a frame ( each frame is different for different images) .I have written a function which uses the images original height and width and gives me customized width and height for that particular frame inorder to restore the aspect ratio.Now I have called that function through onload as images loads on that particular moment.

My feed.hbs( template)

<img src = "{{photo.0.photo_url}}" onload = "OnImageLoad(event);" {{action "imgOverlay0" photo}}/>

Function

function OnImageLoad(evt) {

    var img = evt.currentTarget;

    // what's the size of this image and it's parent
    var w = $(img).width();
    var h = $(img).height();
    var tw = $(img).parent().width();
    var th = $(img).parent().height();

    // compute the new size and offsets
    var result = scaling(w, h, tw, th,false);

    // adjust the image coordinates and size
    img.width = result.width;
    img.height = result.height;
    $(img).css("margin-left", result.targetleft);
    $(img).css("margin-top", result.targettop);
    // console.log("result",result)
    return result;
}

function scaling (w, h, tw, th,false){
   //manipulation with data 

}

But it will not be included in the build of ember as I have kept the function file in bower_compontent.How do I include it in my ember app ?




Use Onload on image tag in ember

I have a template in which photos are being displayed in a frame ( each frame is different for different images) .I have written a function which uses the images original height and width and gives me customized width and height for that particular frame inorder to restore the aspect ratio.Now I have called that function through onload as images loads on that particular moment.

My feed.hbs( template)

<img src = "{{photo.0.photo_url}}" onload = "OnImageLoad(event);" {{action "imgOverlay0" photo}}/>

Function

function OnImageLoad(evt) {

    var img = evt.currentTarget;

    // what's the size of this image and it's parent
    var w = $(img).width();
    var h = $(img).height();
    var tw = $(img).parent().width();
    var th = $(img).parent().height();

    // compute the new size and offsets
    var result = scaling(w, h, tw, th,false);

    // adjust the image coordinates and size
    img.width = result.width;
    img.height = result.height;
    $(img).css("margin-left", result.targetleft);
    $(img).css("margin-top", result.targettop);
    // console.log("result",result)
    return result;
}

function scaling (w, h, tw, th,false){
   //manipulation with data 

}

But it will not be included in the build of ember as I have kept the function file in bower_compontent.How do I include it in my ember app ?




Is there any way to make an Ember service available to all routes, controllers and components?

I have an Ember 2.3.0 application and a service called ui.js. I constantly use this service across many routes, controllers and components. I normally inject the service manually into each route, controller and component by doing this:

ui: Ember.inject.service()

However, it's becoming very tedious to keep injecting it manually. How do I automatically make the UI service available to all routes, controllers and components?




Very slow transition possibly caused by removing table from DOM

I'm using Ember JS 2.3.0, Ember Data 2.3.3 and jQuery 2.1.4 and I'm having an issue when trying to transition away from a page with a HTML table component on it. The table component is populated with data from this Ember Data call:

this.store.query('log', {filter: {
    created_at_from: moment().subtract(1, 'month').format('DD/MM/YYYY'),
    created_at_to: moment().format('DD/MM/YYYY'),
    object: 'IsoApplication'
}})

which having looked in the developer tools "Timeline" and "Network" tabs is resolving in good time. It has no special jQuery events etc attached to it and is simply a plain HTML table made dynamic with Ember.

However, when clicking a "link-to" helper that transitions away from the page with the component on it there is a huge 10 second delay before the destination page renders. During this time nothing seems to happen and having used the developer tools "Timeline" and drilled down it seems that the delay occurs when the "removeFromListeners" function is being called (see attached timeline screenshot). No asynchronous stuff is happening at this point and therefore no loader appears but it seems that tearing down the table is the problem because if I remove the table component from the template the issue disappears. Without the table component the page transitions almost instantly.

enter image description here

I have attached the timeline screenshot to see if anyone can help to pinpoint the possible cause of this problem. Any suggestions would be welcome.

Thanks.




Ember throws an error while injecting a service

I recently upgraded my Ember CLI to version 2.2.0 beta 6 and created a new Ember 2.3.0 project. Within it, I have service called ui which I am trying to inject into a route like this:

import Ember from 'ember';

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

    beforeModel: function() {
        this.get('ui').showMessage('Getting data');
    }
});

Ember logs the following error in the browser:

Uncaught Error: Attempting to inject an unknown injection: `service:ui`

I have checked and made sure that the UI service file - /app/services/ui.js is in fact there. In previous Ember.js projects (Ember version 1.13.0), I would do the exact same thing and it worked. What am I missing? Did anything change? I cannot find any changes in the documentation.




Create a custom function in ember controller

I have created a function for my ember app which do some calculation.But I am not able to use it.

Controller.js

import Ember from 'ember';
export default Ember.Controller.extend({
   ScaleImage(data) { 
      //maniplution with data 
   },
   feedResult:Ember.computed('model',function() {
      dimension = ScaleImage(data);
   });
});

It throws an error

Uncaught ReferenceError: ScaleImage is not defined

If I put function in separate file inside the bower_component and then call the function.It works fine.I want to include the function in my ember project.Because I think while building the ember app and delopying it.The separate function file will be left.




How to get reference to current model in Ember?

I have very simple scenario. I retrieve particular instance of a model

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

and I provide form for editing it:

<h2>Edit project {{model.title}}</h2>
<label>Project title</label> 
<br/>
{{input value=model.title size="50"}}

<label>Project description</label>
{{input value=model.description size="50"}}

<label>Project explanation</label>
{{textarea value=model.full_description cols="50" rows="6"}}

{{#bs-button action="saveProject"}}Save{{/bs-button}}

Then in saveProject action handler I need to have a reference to model that was edited. How can I retrieve it?

Thanks in advance.




mercredi 27 janvier 2016

Component Integration test the relies on another third party component not working

I am getting the following error when running an integration component test. Any ideas why? The only slightly weird thing is that the {{input-mask}} component is used from an addon.

TypeError: (intermediate value).on is not a function at http://localhost:7357/assets/vendor.js:182304:7 at mod.state (http://localhost:7357/assets/vendor.js:152:29) at tryFinally (http://localhost:7357/assets/vendor.js:32:14) at requireModule (http://localhost:7357/assets/vendor.js:150:5) at requireFrom (http://localhost:7357/assets/vendor.js:123:12) at reify (http://localhost:7357/assets/vendor.js:108:22) at mod.state (http://localhost:7357/assets/vendor.js:151:17) at tryFinally (http://localhost:7357/assets/vendor.js:32:14) at requireModule (http://localhost:7357/assets/vendor.js:150:5) at Ember.DefaultResolver.extend._extractDefaultExport (http://localhost:7357/assets/vendor.js:66617:20)

Test:

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('phone-mask', 'Integration | Component | phone mask', {
  integration: true
});

test('it can format landlines', function(assert) {
  assert.expect(1);
  this.set('value', 1111111111);
  this.render(hbs`{{phone-mask value=value}}`);
  assert.equal(this.$('input').val(), '(11) 1111 1111');
});

Component:

import Ember from 'ember';
import layout from './template';
import { startsWith } from '../../utils/elm-helpers';

const  { Component, observer } = Ember;

export default Component.extend({
  layout,

  // public
  value: null,
  format: '(99) 9999 9999',
  iconName: 'phone',
  disabled: false,

  valueUpdated: observer('value', function() {
    if (startsWith(this.get('value'), '04')) {
      this.set('format', '9999 999 999');
      this.set('iconName', 'mobile');
    } else {
      this.set('format', '(99) 9999 9999');
      this.set('iconName', 'phone');
    }
  })

});

Template:

<div class="input-group">
  <span class="input-group-addon">
      <i class="fa fa-{{iconName}}"></i>
  </span>

  {{input-mask mask=format name=name class="form-control" unmaskedValue=value disabled=disabled}}

</div>




Ember Component - Cannot set property tagName of #

I have updated Ember 2.3 recently. In one of our component, We have used 'tagName' as properties like below:

export default Ember.Component.extend({ layout, tagName: 'div' }

It was okay with old Ember. But in the recent one, I am getting the following error.

Uncaught TypeError: Cannot set property tagName of # which has only a getter

Could anybody of you suggest me any clue of the issue.




Creating ember data model in component integration test

I am using a component integration test

moduleForComponent('my-component', 'Integration | Component | my component', {
  integration: true
});

My component accepts an ember-data model. So essentially I would like to do:

this.set('store', Ember.inject.service('store'))
this.set('model', this.get('store').createRecord('employee'));

Then:

this.render(hbs`my-component model=model`);

But when it creates the employee ember-data model, the DS namespace is showing DS.default in the debugger which in turn screws up DS.attr because it is now undefined.




Cross Domain Request w/ Cors

I've got an ember solution, which locally runs on http://localhost:4200. It request data from my WebApi Application, which utilizes Windows Authentication. That currently runs on http://localhost:11470. For some bizarre reason when my WebApi application responds it leaves off content such as: Access-Control-Allow-Origin. Thus throwing the following exception:

XMLHttpRequest cannot load http://localhost:11470/api/Authentication/logins. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

If I look at the request, I clearly see the WebApi application isn't including such data in the header. How can I correct my issue?

// Inside: 'WebApiConfig'
configuration.EnableCors(new EnableCorsAttribute("http://localhost:4200", "*", "*") { SupportsCredentials = true });

// Controller:
[Route("api/Authentication/Logins")]
public IHttpActionResult Login()
{
     if (User.Identity.IsAuthenticated)
          return Ok();      

     return Unauthorized();
}

// Ember Ajax:
Ember.$.ajax({
     type: "GET",
     url: 'http://localhost:11470/api/Authentication/logins',
     crossDomain: true,
     headers:{
          'Authorization': 'WWW-authenticate'
     },
     xhrFields: {
          withCredentials: true
     },
     error: function() { console.log('Error'); },
     success: function() { console.log('Working?'); }
});

I even tried the following:

  • Forcing the header information in the web.config.
  • Custom implementation of IHttpActionResult
  • Custom filter implementation for ActionFilterAttribute.

Those don't hit before the console errors. All that is enabled for the WebApi Application is Windows Authentication, if I navigate directly to localhost:11470/api/authentication/login it prompts me for my Active Directory credentials, then correctly responds.

I've read several documents, such as:

I can't get a solution to reliably work, what am I missing or not understanding? I know it requires the header, but why is the Cors library for WebApi not sending it?




Set environment = 'staging' in Ember deployed with Capistrano 3

I've got a staging environment where I'd like to set a custom set of variables for deploying my Ember.js app and I'm drawing a blank on how to do it correctly. I am using the ember-cli-rails gem. According to the documentation for that:

EMBER_ENV: If set on the environment, the value of EMBER_ENV will be passed to the ember process as the value of the --environment flag.

I'm just drawing a blank on how to set it on the "environment".

/project/frontend/config/environment.js

if (environment === 'test') {
  // Testem prefers this...
  ENV.baseURL = '/';
  ENV.locationType = 'none';

  // keep test console output quieter
  ENV.APP.LOG_ACTIVE_GENERATION = false;
  ENV.APP.LOG_VIEW_LOOKUPS = false;

  ENV.APP.rootElement = '#ember-testing';
}

if (environment === 'staging') {
  ENV.apiHost = '/app-data';
  ENV.contentSecurityPolicy = contentSecurityPolicy;
  ENV.torii = {
    providers: {
      'my-custom-oauth2': {
        apiKey: '1234123412341234123412341234',
        baseUrl: 'http://ift.tt/1SKIxbK'
      }
    }
  };
}

if (environment === 'production') {
  ENV.apiHost = '/app-data';
  ENV.contentSecurityPolicy = contentSecurityPolicy;

Things I've tried so far:

  • Setting export EMBER_ENV='staging' in my deployer user's .profile
  • Setting set :default_env, { 'EMBER_ENV' => 'staging' } in my /config/deploy/staging.rb file.



How do I translate #if type handlebars helpers from ember 1.7 to ember-cli (2.3)

I have this registered handlebars helper in ember1.7 right now.

var get = Ember.Handlebars.get;
Ember.Handlebars.registerHelper('ifCond', function(val1, val2, options) {
    var context = (options.fn.contexts && options.fn.contexts[0]) || this;
    var val1 = get(context, val1, options.fn);
    if (val1 == val2) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

The idea is pretty simple: take first parameter as a context property, second parameter as an actual value, and return a boolean based on their equality. So, for example, if I have a property age on an object user,

{{#ifCond user.age "22" }}
  <h2> Twin Twos!</h2>
{{/ifCond}}

would be a snippet I would use to render the h2 element when the condition is fulfilled.

However, I cannot figure out how to translate such a helper for ember-cli.

I've considered making a component, but I need a conditional, not something that renders a specific set of DOM elements. I feel like I'm missing something. How would I be able to make {{#ifCond}} work in Ember 2.3?

EDIT: I found a helper creation doc that let me to this implementation:

import Ember from 'ember';

export function ifCond(params/*, hash*/) {
    return (params[0] === params[1]);
  // return params;
}

export default Ember.Helper.helper(ifCond);

however, for this to work, I would have to write (in the template)

{{#if (ifCond 1 1)}}
  yep
{{/if}}

Is there still a way to actually use the handlebar helper as we could in ember 1.7 ?




How to inject the Store to my ember component

I am in the situation where i need to inject the store to my component , at least i think this is my need.

This is the situation:

I have component , the code itself does not really matter but i paste it for better understanding:

//components/masonry-plugin.js
import Ember from 'ember';

export default Ember.Component.extend({
  didInsertElement : function(){
    this._super();
    Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
  },

  afterRenderEvent : function(){
    var $grid = this.$('.grid').masonry({
      itemSelector: '.grid-item',
      percentPosition: true,
      columnWidth: '.grid-sizer'
    });
    // layout Isotope after each image loads
    $grid.imagesLoaded().progress( function() {
      $grid.masonry();
    });  
  }
});

This is his own template

<div class="grid">
    <div class="grid-sizer"></div>
    {{#each model}}
        <div class="grid-item">
          <img {{bind-attr src=imgLink}}>
        </div>
     {{/each}}
</div>

This template is imported in an other template photography.hbs by {{masonry-plugin}}

The question is, since in photography.hbs i have access to the module imgLink, because in the route photography.js i create the module consuming the Flickr API, how can i make the module accessible also to the template in {{masonry-plugin}} ?

Hope the explanation is clear

Here also the model img for clarification

var img = DS.Model.extend({
    imgLink: DS.attr('string')
});




InstallError installing ember-cli-rails

I'm new to Ruby so I'm sure there's something I've overlooked, but I don't know what.

I'm trying to install a Rails app in a bundle.

$ bundle install --path vendor/bundle

Many gems work, but

Installing ember-cli-rails 0.7.0
Gem::InstallError: ember-cli-rails requires Ruby version >= 2.1.0.

I think I'm running an acceptable version of Ruby...

$ bundle exec ruby --version
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14]   
$ ruby --version
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14]

Any ideas of what's wrong?




Ember 2 simple polymorphic relations

I have a notes model that I want to attach to one of two other models, customers and suppliers.

In my database I have a foreignType and foreignId field that holds the type and the corresponding ID for the customer or supplier, something like

notes: { {id: 1, body:'bar',foreignType:'customer',foreignId:100},
         {id: 2, body:'foo',foreignType:'supplier',foreignId:100}
       }

That is, a note can be attached to a customer or a supplier.

The convention seems to be that the field be called noteType? I have seen a tutorial where the related type was nested in the JSON, rather then being at the root.

My ember models look like this:

//pods/note/model.js
  export default DS.Model.extend({
    //...
    body: DS.attr('string'),
    foreign: DS.belongsTo('noteable',{polymorphic:true})
  });

//pods/noteable/model.js (is there a better/conventional place to put this file?)
  export default DS.Model.extend({
    notes: DS.hasMany('note')
  });

//pods/customer/model.js
  import Noteable from '../noteable/model'; 

  export default Noteable.extend({ //derived from Noteable class
     name: DS.attr('string'),
     //...
   });

//pods/supplier/model.js
  // similar to customer



// sample incoming JSON
//
{"customer":{"id":2,"name":"Foobar INC",...},
 "contacts":  
    [{"id":1757,"foreignType": "customer","foreignId":2,...},
     {"id":1753,"foreignType": "customer","foreignId":2,...},
     ...],
   ...
  "todos":
     [{"id":1,"foreignType":"customer","foreignId":2,"description":"test todo"}],
  "notes":
     [{"id":1,"foreignType":"customer","foreignId":2,"body":"Some customer note "}]
}

How to set this up correctly?

My notes aren't attaching correctly to the customer model. They show up in the Data tab of the Ember Inspector, but the notes list of any customer is empty.

I can see several possibilities:

  • extend customer/supplier from DS.Model and have a property notes: belongsTo('noteable'), that would mean the belongsTo in notes isn't polymorphic, as there wouldn't be any derived classes, only Noteable itself. Not sure if ember (data) can deal with this nesting correctly.

  • extend from Noteable. what if I want to have other things like addresses or contacts, that can be related to customer or supplier?

  • create duplicate models like customernote/suppliernote, customercontact/ suppliercontact, customer/supplier/employee address. And have the backend return the filtered table/model name depending on the endpoint. I don't like to repeat myself though ....

Ember : 2.2.0
Ember Data : 2.2.1




Combine items in array by their key

I am using Ember Data to get some items for a cart. These items may look something like this

[
  {
    "item_id":"5635",
    "raffle_purchase_id":"1060",
    "item_name":"***",
    "item_desc":"***",
    "item_image":"5635-Ilbt8xNGsD-cropped.png",
    "item_amt":"2",
    "item_type":"raffle"
  },
  {
    "item_id":"5635",
    "raffle_purchase_id":"1061",
    "item_name":"***",
    "item_desc":"***",
    "item_image":"5635-Ilbt8xNGsD-cropped.png",
    "item_amt":"4",
    "item_type":"raffle"
  },
  {
    "item_id":"5635",
    "raffle_purchase_id":"1563",
    "item_name":"***",
    "item_desc":"***",
    "item_image":"5635-Ilbt8xNGsD-cropped.png",
    "item_amt":"2",
    "item_type":"raffle"
  },
  ...
]

Each item here has a different purchase ID that I need to update on the server side so I need to send back all the items to update back to the server. However when I'm displaying these I don't want to show every line of this same purchase over and over again. Rather I want to combine those and calculate the total those purchases cost.

Each item has an item ID, in this case those are the same for these 3 (and potentially more) items, and there might be a handful of other purchases of the same item multiple times that I want to do the same thing to.

Basically I need to get all the items here that have the same ID, get a total sum of their item_amt property, and then combine them and show just one line item with the total.

I'm a little lost on this one as to where to start and where to do this. Currently this return is coming from the route in the model hook so I know I can do whatever processing I need to before actually setting the model. However I want to make sure I keep the original items intact (as I will need to know the unique raffle_purchase_id's) for later when the user is paying for these.




How to set the class of the root div in an Ember application?

I have an Ember 2.3.0 application. When the application is initialized, Ember creates a root div inside which, everything I create is inserted. This div looks like this:

<div id="ember351" class="ember-view"></div>

This element is a first child of the <body> element. I need to be able to set the class of this div. How do I do that?




In Ember automatically route application to error route if template promise returns error

Given a route it is easy enough to get Ember to navigate to an error route if the model promise rejects. Currently I have the simple method of having an error.hbs and /routes/error.js, and if the model promise errors it loads the error page.

I have a situation where the model resolves fine, but one of its relationships does not. This relationship is used in the routes template e.g.

{{#each model.addresses as |address id|}}
  {{address.line1}}
{{/each}}

So http://ift.tt/1PDKs1A returns a 500 error. I see this in the console window, but Ember does not automatically transition to the error page. How can I get it to do this for all promises that reject as a result of a template requesting more data?




develop CMS in Ember js

i am new in emberjs, i feel ember is good and well structured mvc framework,

Is it possible to create a Content Management System in Ember ?

i want to create new pages, section in pages, i thing ember using routes for pages, and i want dynamic pages, the page may have different styles,

this.route('admin',{ resetNamespace: true },function(){
      this.route('dashboard',{ resetNamespace: true }); 
  });

can i dynamically generate routes thank you in advance




Ember: Add conditions in form-element to display field contents

How to add conditions in Ember template. What I want to achieve is like this condition.

if(modalForAdd == true) // if modalForAdd is true then set the model or the property of each input textfield to blank
{
  {{bs-form-element controlType="text" label="Quantity" property=""}}
}
else 
{
  {{bs-form-element controlType="text" label="Quantity" property="model.quantity"}}
}

Here is my code for template

    {{#bs-modal open=openModalForDetails title="Add new Order" body=false footer=false}}
    {{#bs-modal-body}}
       {{#bs-form model=this action=(action "SaveNewOrder" model "this")}}
          {{bs-form-element controlType="text" label="Item SKU" property="model.item" id="item"}} 
          {{bs-form-element controlType="text" label="Quantity" property="model.quantity" id="quantity"}} 
          {{bs-form-element controlType="text" label="Description" property="model.description" id="description"}} 
          {{bs-form-element controlType="text" label="Discount" property="model.discount" id="discount"}} 
          {{bs-form-element controlType="text" label="Coupon" property="model.coupon" id="coupon"}} 
          {{bs-form-element controlType="text" label="Price" property="model.price" id="price"}} 
       {{/bs-form}}
    {{/bs-modal-body}}
    {{bs-modal-footer closeTitle="Cancel" submitTitle="Add"}}
{{/bs-modal}}




mardi 26 janvier 2016

Ember: How to render a template

How to render a certain template by name? Supposed that I have a button, on button clicked event I want to show that template in a modal. Can you guys please guide me.




Ember c3 custom tooltip

I'm using ember-c3 addon (http://ift.tt/1QBduxP) in my ember-cli app to create a chart, so far now it works pretty well, but now i want to create a custom tooltip

{{c3-chart
  data=data
  tooltip=tooltip
}}

i'm using a controller computed property to define data, and wanted to do the same for tooltip this way (to create a custom tooltip is needed an object with a contents property with html value)

tooltip: Ember.computed('model', function() {
    return {
        contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
            return '<div>HTML</div>';
        }
    };
})

But i was wondering how to get a raw template so i don't need to write plain HTML in my controller and achieve something like this

tooltip: Ember.computed('model', function() {
    var html = ...; // How to get a raw template from templates folder?
    return {
        contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
            return html;
        }
    };
})

template might depend on some other variables but the idea is to be able to get the raw html from the template file.

Any guidance will be appreciated!

Thanks in advance.




ember build command fails with error: no such file or directory, lstat ..../ember-cli-test-loader/test-loader

I have recently updated the dependencies in packages.json and bower.json and have run into a similar error like this that i solved by providing an overwrite to the vendorFiles option in my EmberApp:

## ember-cli-build.js
...
module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    vendorFiles: {
      'ember-resolver.js': [
        'bower_components/ember-resolver/index.js' , { //similar error to below was solved like this
          exports: {
            'ember/resolver': ['default']
          }
        }
      ],
      ...
    }
  });
  ...

I have tried a similar solution where I place this code in the vendorFiles property to no good luck :( :

#ember-cli-build.js

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    vendorFiles: {
      'ember-resolver.js': <...>,
      // \/\/\/\/\/\/\/\/\/
      'ember-cli-test-loader': [
        'bower_components/ember-cli-test-loader/index.js', {
          exports: {
            'ember/test-loader': ['default']
          }
        }
      ]
      // /\/\/\/\/\/\/\/\/\
    }
  });

Full output as follows:

ENOENT: no such file or directory, lstat '<...>/my-app/tmp/funnel-input_base_path-http://ift.tt/20rlunJ'
Error: ENOENT: no such file or directory, lstat '<...>/my-app/tmp/funnel-input_base_path-http://ift.tt/20rlunJ'
    at Error (native)
    at Object.fs.lstatSync (fs.js:839:18)
    at symlink (<...>/my-app/node_modules/ember-cli/node_modules/symlink-or-copy/index.js:63:26)
    at Function.symlinkOrCopySync [as sync] (<...>/my-app/node_modules/ember-cli/node_modules/symlink-or-copy/index.js:58:5)
    at Funnel._copy (<...>/my-app/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:398:19)
    at Funnel.processFile (<...>/my-app/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:381:8)
    at Funnel.applyPatch [as _applyPatch] (<...>/my-app/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:298:12)
    at Funnel.<anonymous> (<...>/my-app/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:250:10)
    at Array.forEach (native)
    at Funnel.processFilters (<...>/my-app/node_modules/ember-cli/node_modules/broccoli-funnel/index.js:249:9)

I'm not sure from the output where i would find out what is happening. I'm new to broccoli (coming from grunt and gulp) and also new to ember-cli




Wait for other interaction to happen before resolving RSVP

I have a component that on a swipe will send an action upward to the parent route/controller to handle some ajax functionality. This component has some UI that gets set to a loading state to show the user things are happening.

callAjaxAction() {
  this.setProperties({working:true});
  Ember.RSVP.cast(this.attrs.action()).finally(() => {
    this.$('.draggable').animate({
      left: 0
    });
    this.setProperties({working:false});
  });
}

In this case the controller catches the action specified on the component definition and calls an ajax function to get some data to display in the page

// in the controller action
return Ember.RSVP.Promise((resolve,reject) => {
    Ember.$.ajax({
      type: 'get',
      dataType: 'json',
      url: `http://***/api/paysources/user/697?key=${ENV.APP.api_key}`
    }).then((response)=>{
      this.setProperties({
        'cards':response.user_paysources,
        'showCards': true
      });
    },(reason)=>{
      reject();
      this.get('devlog').whisper(reason);
    })
  })

When the endpoint returns data it gets set to a property on the page (which another component picks up and displays) and then sets a property on the controller to do some more UI to this page.

I then have a click listener that will set a selectedCard property to a card the user has chosen and when that happens I need to fire off another ajax function that actually pays for items in a cart. Once this ajax call resolves I need to send back to the original component (the one that swipes and sets a loading state) that everything has been resolved and it can reset it's UI.




ember component does not update template

I'm trying to build a component that receives an ember array of objects (each of them representing a comment), and returns an ember array of rows (each row is an ember array of 2 comments); the purpose is to format the original array of objects received into a HTML grid layout:

//main template
{{#column-layout list=comments as |comment|}}
    <div>
        <h5>{{comment.username}}</h5>
        <p>{{comment.content}}</p>
    </div>
{{/column-layout}}


//column-layout template
{{#each rows as |row|}}
    <div class="row">
        {{#each row as |item|}}
            <div class="col s6">  // column 50% width
                {{yield item}}
            </div>
        {{/each}}        
    </div>
{{/each}}

and the column-layout component's javascript:

export default Ember.Component.extend({
    init: function() {
        var self = this;

        self._super();

        var data = this.get('list');
        var itemsPerRow = 2
        var rows = Ember.A();
        var row = Ember.A();

        if (data) {
            data.forEach(function(item, index) {
                if (index % itemsPerRow === 0 && index !== 0) {
                    rows.push(row);
                    row = [];
                }

                row.push(item);
            });
        }

        if (row.length > 0) {
            rows.push(row);
        }


        // manage scroll after adding or removing items
        self.get('list').addArrayObserver(Ember.Object.create({
            arrayWillChange: Ember.K,
            arrayDidChange: function(array, start, removeCount, addCount) {
                if (addCount > 0) {
                    var row = Ember.A();

                    row.push(array[start]);
                    rows.push(row);
                    self.set('rows', rows);
                }
            }
        }));

        self.set('rows', rows);
    },

});

The thing that doesn't work here is that the template does not update adding the new comment when the arrayObserver fires;

the weird thing is that if I do self.set('rows', []) in the "arrayDidChange" function, the template updates, removing all comments as expected; but self.set('rows', rows) has no effect event if "rows" is the correctly updated array with the new row;

Can someone explain what am I doing wrong here?




How do I make dynamic classNames in an ember 2.0 component?

For example: Ember components allow you to add a classNames array and those classes will be added to the main div of the component. say we have this component called new-div export default Ember.Component.extend({ classNames: ['container'] });

then if you inspect this component when rendered you will see: <div id="ember595" class="ember-view container"> ... </div>

this is fine but my issue is what if i want to use this component as a fluid container sometimes and sometimes I might want to make it a jumbotron etc...

Is there a way to do this in the html and have the component.js apply it correctly?

like: {{new-div extra-classes='class1,class2'}}

then in the component.js:export default Ember.Component.extend({ classNames: [this.get('class-names')] });




Formatting currency in Ember

I have a form with several input fields for entering amounts of money and shows the total at the bottom of the screen. I would like for the user to only be able to type in numeric digits [0-9], then a decimal ., and then a maximum of two more digits.

At first, I used the Ember addon ember-inputmask which correctly formats the currency as I needed, but if I clicked on an input and clicked out without entering a number or if I only entered part of a number and clicked else where the total would equal NaN.

I have also attempted to import the jQuery plugin autonumeric.js through npm and use that but with no success.

What is the best approach to only allow currency to be typed in an input field in Ember?

Is there a better addon or resources on how to accomplish this?




Ember 2.x get model's relationships at subroute of that model

Imagine that I have two models, Author and Book.

// models/author.js
DS.Model.extend({
  name: DS.attr(),
  books: DS.hasMany('book')
});


// models/book.js
DS.Model.extend({
  title: DS.attr(),
  author: DS.belongsTo('author')
})

It would be nice to have an endpoint at /api/authors/{authorID}/books to be able to get all of the authors books in one batch request, instead of making multiple calls to /api/books/{bookID}, but it doesn't seem that ember supports this. It is possible to do /api/books?authorID={authorID}, but that would lose some of the benefits of the store.

Is there an Ember idiomatic way of doing /api/authors/{authorID}/books? Again, the goal is to be able to make one batch request to get all books for an author instead of making one call for every book in the author's hasMany list.

For a little more context, I have the following routes structure:

// router.js
...
this.route('authors', function() {
  this.route('author', { path: ':id' }, function() {
    this.route('books');
  });
});
...

In the 'authors' route I will load all of the authors. I do not want to synchronously load their related books, yet, as the list is potentially massive and not used on this route.

In the author route I'm using data of the author already retrieved (the name, in this case).

In the books route I would like to finally load all of the author's related books without needing to send a single request per book.




Create multiple arrays from one set

I have an array of items, each have an item_type property that could be one of four different types (this is a cart of items). When I attempt to "pay" for the items in the cart, I need to separate all the items remaining into arrays of each item type to send back to the server so the proper tables can be updated. I was just going to use a map to do this but that would require multiple passes (at least the way I was thinking I needed to do it) but is there a quicker way to take one array and split it into multiple arrays based on a property?

Specifically I need to know which array is which (which one has raffle tickets, donations, etc.) so I can post them to the server with the correct property name so the server knows what array is what and how to proceed with each.

Currently in ember this is how I am working through this. Not a lot of code but still I wonder if there is some refactoring that can be done here

// ARRAYS OF CLASSES
itemsArray: Ember.computed.filterBy('model.items','item_type','bid'),
donationsArray: Ember.computed.filterBy('model.items','item_type','donation'),
ticketsArray: Ember.computed.filterBy('model.items','item_type','ticket'),
rafflesArray: Ember.computed.filterBy('model.items','item_type','raffle'),

// ARRAYS OF JUST CLASS IDS
itemIds: Ember.computed.mapBy('itemsArray','id'),
donationIds: Ember.computed.mapBy('donationsArray','id'),
ticketIds: Ember.computed.mapBy('ticketsArray','id'),
raffleIds: Ember.computed.mapBy('rafflesArray','id'),




Changing the view of a div created by loop without re-running the loop in ember.js

How can I change the view of a created by a loop which observes a change in its attribute , without changing the view of other created by the loop .

I am looping an array variable to display a set of list in each div .

{{#each val in property1}}

    <div class="grid1">
       {{val.value}}
     </div>
{{/each}}

Suppose my property1 looks like this

  property1:function(){
   array1 = [{
      value:'person1',
      address:'place1' 
  },
   {
      value:'person2',
      address:'place2' 
  }] 
 return array1;
}.property('flagValue')

Now the on changing the flagValue , property1 is called again and the DOM also gets updated. HOW CAN I OBSERVE THE address of a particular index in array1 object and change the view of the associated to that index without re-running the whole loop again.




Ember .get doesn't return correct value

So i have this ember object "lineup", when i use

lineup.get('stations').length = 396

but it is wrong, if i inspect that object, and use _data

lineup._data.length = 429

it is the correct one,

Lineup stations is got from ember-data request payload manipulation like this

if (payload.stations) {
     payload.stations = payload.stations.map(function(s) {
         s.logo = s.logoFilename ? 'http://ift.tt/1NxbTCC'+s.logoFilename : null;
         delete s.logoFilename;
         return Ember.Object.create(s);
      });
}

any ideas?




lundi 25 janvier 2016

How do I render multiple outlets in one template file using ember 2.3

I'm trying to render multiple .hbs snippets into their respective outlets. However, the following renderTemplate does not work:

renderTemplate: function() {
     // default behavior, renders the home template
     this.render(); 
      this.render('hero', {    // render the `hero` template
       outlet: 'hero'  // using the outlet named `hero`
     });
   }, 

The template file in question looks like this:

{{outlet 'hero'}}
{{outlet}}

This actually renders the default template (this is the index route) twice: once in the hero outlet, and once in the regular outlet.

This seemed to work in ember1.7, even if the hero outlet was included in the application.hbs template. Not quite so with ember2.3.

How would I make this work?




how to get session data created by auth0 in ember 2.3

I am using ember 2.3 (and ember-data 2.3); I'm setting up a simple user auth process using Auth0. Nothing fancy yet, just installed auth0 according to :

http://ift.tt/1OLRvl4

Now, my setup is pretty much exactly the same as the project given here. However, it seems that I can only access the session from application.hbs and not any other template. Or route. Or anything else.

So this handlebars snippet:

{{#if session.isAuthenticated}}
  {{session.data.authenticated.profile.name}}
{{else}}
  NOPE
{{/if}}

works on application.hbs but nowhere else. This does not make sense to me; if auth0 itself says that session.data can be accessed from any template, and that such a handlebars snippet even exists, there must be something I'm missing. I need to be able to show certain portions of the client side as well as restrict some actions based on the currently signed-in user (and whether someone is actually signed in ), all of which are included in the session.data object.

It doesn't seem appropriate to pass this object to every component I'm going to create, and the only way I can think of getting this data right now is to manually get it from localStorage. I could perhaps make this manual process a mixin and have it included everywhere but before I try to find roundabout solutions, I want to make sure that I'm not missing something in the implementation itself.

How would I be able to access the session token throughout the application aside from application.hbs itself?