jeudi 31 décembre 2015

Ember-Cli-Mirage 404

Just followed the documentation but every time I navigate or call to the url, it returns 404 for me

// app/mirage/config.js
export default function() {

  this.get('/api/users', function() {
    return {
      users: [
        {id: 1, name: 'Zelda'},
        {id: 2, name: 'Link'},
        {id: 3, name: 'Epona'},
      ]
    }
  });

}

Uncaught UnrecognizedURLError: /api/users

Thanks for your help.




Ember >2.2.0 getting regeneratorRuntime is not defined

so I was working with an iterator inside a service with Ember. The code worked using the old style scripts I cannot use the ES2015 style

ReferenceError: regeneratorRuntime is not defined

    stuff[Symbol.iterator] = function *(){
        debugger;
        let properties = Object.keys(this);
        for(let p of properties){
            yield this[p];
        }
    };

I know this is because of the new '*' operator on the function. I have seen answers http://ift.tt/1mTz84G that describe having to load a browser-polyfill npm but I'm a little unclear how to get this to work inside the ember framework. Has anyone done this successfully? or should I just abandon until Ember supports it.




How to know if a 'click' event was actually the user trying to highlight some text?

I have a list of items, when clicked, fires an event which hides the clicked item. However, there's text within the item, which the users sometimes try to highlight, in order to copy the text. But the event fires when they finish highlighting, thus, hiding the text they wanted to copy. I still want the event to fire if the user actually clicks on the text, but not if they click-hold and highlight.

Is it possible to differentiate this in jQuery? Bonus, my website is on Ember.js, if you happen to know that it's achievable using Ember's action helper, let me know!

Thanks!




Recursive request of related objects

In one of my templates, I am doing:

{{#each model as |product|}}
    {{product.project.name}}
{{/each}}

EmberData does the right thing, and for each product it fetches the related project. But then, I have tried to do the following:

{{product.project.artist.username}}

Now projects are requested, but the related artist is not requested from the backend. Have I hit any kind of depth limitation? Is this specified somewhere?

I don't think I have any bug in my code. My models are just:

// product.js
export default DS.Model.extend({
    ...
    // Relationships
    project: DS.belongsTo('project'),
}

// project.js
export default DS.Model.extend({
    ...
    // Relationships
    artist: DS.belongsTo('user'),
}

// user.js
export default DS.Model.extend({
    username: DS.attr('string'),
    ...
});




Dasherize properties for JSONAPI

I have this model in my drf backend:

class Product:

    price_range = ...

I am using EmberData with the JSONApi serializer. I have just found out that JSON API requires dasherized properties. So I need to tell drf:

JSON_API_FORMAT_KEYS = 'dasherize'

And the property gets serialized in the JSON as:

price-range

Then, EmberData does its dance, and I get the Ember model property:

import DS from 'ember-data';

export default DS.Model.extend({
    ...
    priceRange: DS.attr('number'),
    ...
});

(the old RESTSerializer was expecting priceRange in the JSON, if I recall properly)

So, we go from price_range -> price-range -> priceRange (which is pretty crazy if you ask me). I found all this by trial and error. For drf the corresponding settings are documented here.

Where is this documented for JSONApi, EmberData and Ember? I would like to make sure I have really understood this, and that this is also the case for relationships. The related drf config setting would be:

JSON_API_FORMAT_RELATION_KEYS = 'dasherize'




Not able to implement center scrolling in ember-modal-dialog

I have designed a modal dialog in ember app using ember-modal-dialog addon.I want to implement the center scrolling in my dialog.But Not able to do it.

feed.hbs

<p {{action "toggleModal" photo }}>{{photo.0.numFives}}</p>
            {{#if photo.0.dialogShowing}}
              {{#modal-dialog translucentOverlay=true
                  targetAttachment='none'
                  container-class='centered-scrolling-container'
                  overlay-class='centered-scrolling-overlay'
                  wrapper-class='centered-scrolling-wrapper'}}

              <p>People who like this</p>
              <button class="close" {{action 'dialogClose' photo}}>X</button>
              <img src = "images/shape-line-separator.png" style = "width:340px;height:1px">
              {{#each model.feed.fiver as |fiver|}}
                  <div class="col-sm-12">
                    <div class = "col-sm-4">
                      <div class = "pr">
                        <img src = "{{fiver.dp_url}}" onload = "OnImageLoad(event); "/>
                      </div>  
                    </div>
                    <div class = "col-sm-3"> 
                      <p class="username">{{fiver.full_name}}</p>
                      <p class="userkarma">{{fiver.likes}}  like</p>
                    </div>
                    <img src = "images/shape-line-separator.png">
                  </div>
              {{/each}}
              {{/modal-dialog}}
            {{/if}}

css

.centered-scrolling-wrapper {
  position: fixed;
  z-index: 99;
  height: 100vh;
  left: 0;
  right: 0;
  top: 0;
  overflow-y: scroll;
}

.centered-scrolling-overlay {
  display: flex;
  display: -webkit-flex;
  align-items: flex-start;
  -webkit-align-items: flex-start;
  justify-content: center;
  -webkit-justify-content: center;
  min-height: 100vh;
  padding: 10em;
  position: relative;
  height: auto;
}

.centered-scrolling-overlay.translucent {
  background-color: rgba(35, 31, 32, 0.81);; 
}

/* basic modal style (an example, this is not necessary for the centering) */
.centered-scrolling-container {
  position: relative;
  background-color: #343031;;
  border-radius:2px;
  width:360px;
  max-height:250px;
  box-shadow:0 0 0px;
  padding:0px;
  top:25%;
}

In above code the dialog box appear but it accumulates the data outside the max-height and not like center-scrolling.The dialog box is also doesn't fix at one point.I want to fix the dialog box at one point and when I SCROLL




Use of backtick in ember computed properties

The guides show a computed property written with backticks. I am not sure if they are necessary.

Could this:

fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
})

Be rewritten as this:

fullName: Ember.computed('firstName', 'lastName', function() {
    return this.get('firstName') + ' ' + this.get('lastName');
})

?

For me, that's less obscure. What are the plus / cons of each method?




In Emberjs, how do you use in the template file, properties defined in the route?

Say i have a route file like:

import Ember from 'ember';

export default Ember.Route.extend({
    [...]
    password: "...",
    [...]
});

How do i use the password property in a template?
If i use {{password}} it does not work, however, if i define a controller with a password property, i can then use {{password}} in the template, but given the fact controllers shouldn't be used anymore, what are my options?

I know that i can do something like this in the route:

import Ember from 'ember';

export default Ember.Route.extend({
    model(){
       return {
            password: "...",
       }
    },
});

And then access {{model.password}} but i don't think this is the way to go here.




mercredi 30 décembre 2015

why ember g blueprint

When I do ember g blueprint <blueprint-name> --in-repo-addon <in-repo-addon-name>, generated blueprint code not in lib/. Is it a right behavour?




How to delay or only set a computed property once a promise has been resolved?

I have an Ember app with a computed model property that I am looking to use in a template. For the purpose of the example, at the moment, I am just logging it in the template to test to the output:

{{log post.content}}

In the model, the computed property "content" calls a getMD ( get markdown ) function:

var Post = DS.Model.extend({
  mdURL: DS.attr('string'),
  content: function() {
    getMD(this.get('mdURL')).then(function(md) {
      // On success
      return md;
    }, function(reason) {
      // On fail
    });
  }.property('content')
});

function getMD(url) {
  return new Promise(function(resolve, reject){
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url);
    xhr.onreadystatechange = handler;
    xhr.responseType = 'text';
    xhr.setRequestHeader('Accept', 'application/text');
    xhr.send();

    function handler() {
      if (this.readyState === this.DONE) {
        if (this.status === 200) {
          resolve(this.response);
        } else {
          reject(new Error('getMD: `' + url + '` failed with status: [' + this.status + ']'));
        }
      }
    };
  });
}

The promise is ultimately returning the data but it is happening too late. The computed property in the template has already come through as undefined.




Ember-cli-mirage not showing any data with get

I am learning Ember and I am getting stuck on making the mock api with ember-cli-mirage. I modified the config file as specified in the ember tutorial as well as on the ember-cli-mirage site, but everytime I hit the endpoint I get nothing. Here is my current config file

export default function() {
this.get('/api/users', function() {
return {
  users: [
    {id: 1, name: 'Zelda'},
    {id: 2, name: 'Link'},
    {id: 3, name: 'Epona'},
  ]
}
});
}

Like I said, when I go to /api/users it is just a blank page. Am I missing something here?

Thanks!




How declare a constants file with Ember.js

how would one create a constants class or helper in Ember?

something like create a constants.js and add

export const testme = 3;
export const testtoo = 4;

then in a controller I'd

import constants from 'constants';




Ember: Reinstantiate bootstrap tooltip after DOM change

I have an Ember app coupled with Bootstrap. I've got the tooltips working ok for the rest of my application, but it never instantiates for the elements that I have from within handlebars conditionals.

View

 didInsertElement: function(){
   Ember.$('[data-hover="tooltip"]').tooltip({trigger:'hover'});
 }

HBS

{{#if propertyIstrue}}
    <a href="#" title="Show Me Something" data-hover="tooltip" data-placement="left">Hover These</a>
{{/if}}

So basically propertyIsTrue is a property that gets set to true when the user clicks another button. When the link shows up, the tooltip isn't applied. I need to fix that some how.

I'm using Ember v1.13. Upgrading isn't an option right now.




Ember - triggerEvent helper

I'm having trouble triggering a "change" event in an ember acceptance test.

I have a rangeslider with an observed 'value' property. On change, the slider sends an api request which updates the url with params based on the slider value.

I am able to change the value of the slider in my test using jQuery, which successfully updates the slider in the UI...

$("#slider").val(3.0).change();

...but the change event isn't fired, so no api call. This same setup is working fine for similar tests where I am able to use "click" or "fillIn" to trigger a request.

I've tried using both the run loop and the triggerEvent helper (see below) but am having no luck.

    // 1. using the run loop -- updates UI, but no change event fired

    Ember.run(function() {
      $("#gpa-slider").val(3.0).change();
    });
    andThen(() => {
      assert.equal(currentURL(), "/athletes?gpa=3.0")
    });


    //2. using triggerEvent helper -- 
    //   doesn't update UI, slider value, or trigger change event

    triggerEvent('#gpa-slider', 'change', {value: 3.8} )

    andThen(() => {
      assert.equal(currentURL(), "/athletes?gpa=3.0")
    });

Am I setting up triggerEvent() incorrectly? Is there a better way to handle this?




How to add Css Class to item inside Ember's {{#each}} loop, according to index? - Ember.js

I have a Ember app with side-menu. The menu items in the html are based on Ember's {{each}} loop. When user select a menu-item I want to add this item active class.

How do I add css class to single item inside Ember's {{each}} According to condition from the controller.

Html/Hbs:

<ul>
   {{#each menuItem in sideMenuItems}}
      <li {{bind-attr class="isActive: active-class"}} {{ action 'selectMenuItem' _view.contentIndex }}>
         {{ menuItem.text }}
      </li>
   {{/each}}
</ul>

Controller:

Ember.ObjectController.extend(
{
   selectedMenuIndex: 0,
   isActive: function()
   {
      return (this.get('selectedMenuIndex') == ???);
   }.property('???'),

   actions:
   {
      selectMenuItem: function (itemIndex)
      {
         this.set('selectedMenuIndex', itemIndex);
      }
    }
}




jsonapi + ember 2.0 + pagination

How to do pagination in latest version of ember-data (v2.2) and a jsonapi backend? I am in control of the backend implementation so I can implement any strategy, but I would prefer to follow the standard as described here:

http://ift.tt/1ISH8KN

However, that description is a bit cryptic to me without an example.

And how to handle that smoothly on the client (ember) side? Is there some built in stuff in ember-data to process the paging-links?




How to send the requests to server to get the data for my modal dialog in ember

I am using ember-modal-dialog addon for the dialog features in my app.Now the data shown in dialog is requested from server.So every time I click on button it should request the server and show the received data.

feed.hbs

{{#each feedResult as |feed|}}

<p {{action "toggleModal" feed.fivers_pk }}> {{feed.numFives}} </p>
   {{#if isShowingModal}}
       {{#modal-dialog close="toggleModal"}}
           <p>People who Hi-Fived this</p>
           <img src = "images/shape-line-separator.png">

                 Data from server

       {{/modal-dialog}}
   {{/if}}

{{/each}

Controller.js(feed.js)

import Ember from 'ember';
import raw from 'ic-ajax';

const { service } = Ember.inject;

export default Ember.Controller.extend({
     session:service('session'),
     isShowingModal: false,
     fivers:[],
     feedResult:Ember.computed('model',function() {

            SOME MANIPULATION WITH DATA
     }),

     actions:{

      toggleModal: function(fiverpk) {
         this.toggleProperty('isShowingModal');
         console.log(fiverpk);
         raw({
            url: "http://ift.tt/1QZarQQ"+fiverpk+"/fivers/",
            type: 'GET',
        });
  }, 
}
});

I am able to make the request to server and receive the data through the ajax call in actions.But where and how should I store it.So that I can use it in modal-dialog when it opens.




How to use datePicker with ember-rails gem in rails

In one of my rails application, I am using ember-rails gem, And in that application I have requirement to use datePicker, I had tried to use "ember-pikaday" ember.js addon for date picker , but not able to include it with my rails application.




how to do pagination in ember js with json api response

give me a code for integration of ember js with pagination json api . i have created a pagination class with total no of pages and links like next,last.

i m using this code for integration but its not working .

extractMeta: function(store, typeClass, payload) {
     alert("hellooooooooooooooo");
        if (payload && payload._pagination) {
          store.setMetadataFor(typeClass, payload._pagination);
          delete payload._pagination;
        }
      },




EmberJs - How and where to study?

I have started my hands on Ember.js . I have googled and found few tutorials on it. But still finding it difficult. Can anyone suggest me , the order in which things have to be learned like first routing(router,route) then next next. And also learning the syntax, various other functions used. From the very basic to advanced. Note: I am a beginner to JavaScript and have a level1 understanding of it. Thanks in advance for your help.




mardi 29 décembre 2015

How to get "to" or "from" route within liquid-fire transition?

I'm building a liquid-fire transition that changes behavior depending on the "to" and/or "from" route, but can't figure out how to get either routeName from within the transition.

Might anyone know how to get the "to" or "from" route names from within the transition?




Uncaught TypeError: Cannot read property 'forEach' of undefined(anonymous function) in ember shortcut lib

I am using the latest version of ember like :

<script src="js/libs/ember-template-compiler.js"></script>
    <script src="js/libs/ember.debug.js"></script>
    <script src="js/libs/ember2.2.0.js"></script>
    <script src="js/libs/ember.min2.2.0.js"></script>
    <script src="js/libs/ember-data.min2.2.1.js"></script>
    <script src="js/libs/handlebars-v3.0.0.js"></script>
    <script src="js/libs/ember-shortcut.js"></script>

when i referencing my site I am am getting an error

Uncaught TypeError: Cannot read property 'forEach' of undefined(anonymous function) @ ember-shortcut.js:51(anonymous function) @ ember-shortcut.js:191 ember-template-compiler.js:1505 DEBUG: -------------------------------




Using moment.js with Ember, Ember-CLI

I have been trying to get the moment.js library to work with an Ember application using the Ember-cli. Note I am fairly new to ES2015.

Ember 2.2.0 Ember-cli 1.13.13

my ember-cli-build

/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
    var app = new EmberApp(defaults, {
        //options
    });

    app.import('bower_components/moment/moment.js');

    return app.toTree();
};

and my .jshintrc

"predef": [
    "document",
    "window",
    "-Promise",
      "moment"
  ],

and my controller

/* global moment:true */
import Ember from 'ember';

export default Ember.Controller.extend({
    firstName: null,
    lastName: null,
    day: function () {
        return moment('Dec 25, 1995');
    }.property()
});

I always get an error that 'moment' has not been defined. I read that the latest moment.js has stopped producing a global 'moment' but I'm not sure what to do about it.

The builds work. If I pull up the generated vendor.js I can see the complete contents of the moment.js file in it. However when I look at vendor.js in the chrome debugger the contents are omitted. I wasn't sure if this was due to some optimization.




setup Personal Computer(Ubuntu) as a server for my Rails App

I have a PC at home that I do not use. I would like to setup this computer as a server to host my personal applications to be accessed from the internet. At first, I have one Rails App as the backend API and an Ember.js App as the client app. How can I do this? I have no idea where to start.




emberJS squashing nwJS require() method

I have a nwjs application that points to a web address that contains an ember application. Inside the ember application i need to get access to the node context to see what OS the user is running in order to do an update check. I do that in an initializer like so.

require('os')

Unfortunately i get this:

Error: Could not find module `os` imported from `(require)`

It appears that ember's require() method is squashing the one set by nwjs. I can confirm this by changing the nwjs window to point to google.com, setting the "node-remote" to "*", and then trying to run the require('os') command again. In this instance the module is resolved perfectly.

Ember's code reflects this. http://ift.tt/1YMvTwR

Is there another way to access the proper require() or do i need to create a "node-main" file and just do a

window.nodeRequire = require




Push object to EmberJS Data Store

I would like to know how to push record to the Ember Data Store without using the adapter.

For now every time I'm using this.store.push({type: type, data: data}) the store sets the flag hasDirtyAttributes to true.

As workaround I'm using this.store.findRecord(type, id); to get the record updated from the server but I don't need that because the data I have already came from the server.




Ember tooltip over d3 and html element - with variable content

I need tooltip plugin for ember, which i put just one-time per component and then i could change content of tootltip from component and show it under current hovering element. I have charts in d3 and i need on hover to each element of chart show tooltip with detail of element, this tooltip should stay showed if user moves to tooltip.

Any idea? Thanks!




Ember-CLI-Mirage enforcing JSON:API?

Stumped on a couple failures and want to know if I'm understanding Mirage correctly:

1.In ember-cli-mirage, am I correct that the server response I define should reflect what my actual server is returning? For example:

this.get('/athletes', function(db, request) {
  let athletes = db.athletes || [];
  return {
    athletes: athletes,
    meta: { count: athletes.length }
  }
});

I am using custom serializers and the above matches the format of my server response for a get request on this route, however, on two tests I'm getting two failures with this error: normalizeResponse must return a valid JSON API document: meta must be an object

2.Is mirage enforcing the json:api format, and is it doing so because of the way I'm setting up the tests?

For example, I have several tests that visit the above /athletes route, yet my failures occur when I use an async call like below. I would love to know the appropriate way to correctly overwrite the server response behavior, as well as why the normalizeResponse error appears in the console for 2 tests but only causes the one below to fail.

test('contact params not sent with request after clicking .showglobal', function(assert) {
  assert.expect(2);
  let done = assert.async();
  server.createList('athlete', 10);

  //perform a search, which shows all 10 athletes
  visit('/athletes');
  fillIn('.search-inner input', "c");

  andThen(() => {
    server.get('/athletes', (db, request) => {
      assert.notOk(params.hasOwnProperty("contacts"));
      done();
    });

    //get global athletes, which I thought would now be intercepted by the server.get call defined within the andThen block
    click('button.showglobal');
  });
});

Result:

✘ Error: Assertion Failed: normalizeResponse must return a valid JSON API document:
    * meta must be an object
         expected true

I tried changing my server response to a json:api format as suggested in the last example here but this looks nothing like my actual server response and causes my tests to fail since my app doesn't parse a payload with this structure. Any tips or advice must appreciated.




Bulk commit in ember js?

I have 7k amount of data and i am using ember data. I am using following code cleanList.forEach(function(dncInfo) { let email = dncInfo.email; if (!email) { email = dncInfo.domain; } let type = (dncInfo.email) ? 'PERSON' : 'COMPANY'; let donotcontactInfo = controller.store.createRecord('lead-generation/md-donotcontact', { "pattern": email, "type": type, "status": 'manual' }); let promise = donotcontactInfo.save(); uploadedList.push(promise); promise.then(function( /* info */ ) { // }); });

When i use these in huge amount of data like 7k i get error Error net::ERR_INSUFFICIENT_RESOURCES but if use the same request for small data it works. What is the best way to handle huge amount of data in Emberjs? Is there any Bulk commit in EmberJs ?




rails ember-cli No route matches [GET] > "/javascripts/emberFrontend/vendor.js"

I am new to Ember and I'm trying to understand how the asset building works. I have an existing Rails project that is in the middle of conversion to Ember, with ember-cli.

ember 1.13 ruby 2.1.6 rails 4.1.6

I keep getting these errors when trying to access ember pages, and I'm trying to isolate when, and what causes them:

Started GET "/javascripts/emberFrontend/vendor.js" for 127.0.0.1 at 2015-12-28 17:10:16 +0200

ActionController::RoutingError (No route matches [GET] "/javascripts/emberFrontend/vendor.js"): ...

Started GET "/javascripts/emberFrontend/ember-frontend.js" for 127.0.0.1 at 2015-12-28 17:10:16 +0200

ActionController::RoutingError (No route matches [GET] "/javascripts/emberFrontend/ember-frontend.js"):

for example, I take a page that is rendering fine and logs:

Started GET "/assets/emberFrontend/vendor-b0892280be71c70102741f9d7feb0532.js" for 127.0.0.1 at 2015-12-28 17:53:15 +0200

Started GET "/assets/emberFrontend/ember-frontend-affc24729a1c2e1a0a6a56334d2bb16a.js" for 127.0.0.1 at 2015-12-28 17:53:15 +0200

And I make a change in the template code from:

<li class="reportsTab"><a href={{urls.reports}}>Reporting</a></li>

to:

<li>{{#link-to "merchant.reports"}}Reporting{{/link-to}}</li>

In order for one of the page tabs to direct to the ember code instead of the old one, similar to other changes made on that page. This change causes the errors above, and the browser page is blank.

What is puzzling me is that if I revert the change while the rails server is running, and then restart it - it doesn't stick, but if I stop the server, than make the change and rerun it, it does. Clearly I am missing something in understanding how the ember server is building the assets, but I can't figure it out from any guides.

Also (and possbily related), my */emberFrontend/tmp directory doesn't clean.




Use Ember components with Require.js

Is it possible to use Ember Components without ember-cli, and load them dynamically with require.js?

We have to use require.js for legacy reasons and would eventually migrate from it, but we need some time. Currently we use Ember Views with require.js just fine, can't I can't figure out how to switch them to controllers.




Undefined method 'config' for ActiveModel::Serializer

I am trying to follow several tutorials to connect Rails 5 in API mode with Ember application but in all of them once I create new initializer and use:

ActiveModel::Serializer.config.adapter = :json

I get "undefined method 'config' for ActiveModel::Serializer ..." I am using 'active_model_serializer' gem since Ember expects a json with a root object instead of plain json




lundi 28 décembre 2015

Why does an ember link-to combined with queryParams cause this exception: "TypeError: delegate is not a function"?

Somehow, I am getting a conflict between the link-to helper, an aliased controller property, and a declared query parameter. Specifically, I've defined a controller with a query parameter bound to the property of an injected controller. Then I get an exception if I set the injected controller's property BEFORE initializing the controller with the query parameter.

Basically, I want to be able to navigate from one route to another but by first setting a query parameter in the route I'm navigating to. Earlier, I tried doing this by simply passing queryParams as an optional argument to the transitionToRoute() method, but this is not available when already at that route. And besides, I'm very curious why this exception is turning up at all. The code seems innocent enough!

The heart of the code are the two controllers.

// application.controller.js
export default Ember.Controller.extend({
  appValue:'before',
  actions: {
    clickMe() {
      this.set('appValue', 'after');
    }
  }
});

and

// my-route.controller.js
export default Ember.Controller.extend({
  queryParams: ['myValue'],
  application: Ember.inject.controller(),
  myValue: Ember.computed.alias('application.appValue')
});

Now consider this template

// application.template.hbs
{{link-to 'application' 'application'}}
{{link-to 'my-route' 'my-route'}}
<button {{action 'clickMe'}}>clickMe</button>
{{appValue}}

If I load the / route to start, click the button and then the my-route link, I get this exception.

TypeError: delegate is not a function
at _emberRuntimeMixinsController.default.reopen._qpChanged (ember.debug.js:23076)
at Object.apply (ember.debug.js:22250)
at Object.sendEvent (ember.debug.js:16127)
at notifyObservers (ember.debug.js:19666)
at propertyDidChange (ember.debug.js:19493)
at Object.ChainWatchers.notify (ember.debug.js:13756)
at chainsDidChange (ember.debug.js:19582)
at propertyDidChange (ember.debug.js:19492)
at ember.debug.js:19568
at Meta._forEachIn (ember.debug.js:17831)

And yet, if I first navigate between the links back and forth, before clicking the button, then there is no exception!

Here is an Ember Twiddle to illustrate. http://ift.tt/1PtzvfB




Lazy loading image component not updated when is in the view port

I created a component that will load itself when it is in the viewport. The problem that I am facing is that it is not updating itself once it is in the viewport. The ​mixing job is only way to check if the component is in the view port or not. As for now this is ONLY working every time I refresh the page. I would like the component to be updated when the user scrolls down instead of refreshing. Would appreciate if someone could set me on the right path.

Mixin:

​App.InViewportMixin = Ember.Mixin.create({
    enteredViewport: function(){
       var win = $(window);

        var viewport = {
            top : win.scrollTop(),
            left : win.scrollLeft()
        };

        viewport.right = viewport.left + win.width();
        viewport.bottom = viewport.top + win.height();

        var bounds = this.$().offset();
        bounds.right = bounds.left + this.$().outerWidth();
        bounds.bottom = bounds.top + this.$().outerHeight();

        return (!(viewport.right < bounds.left || viewport.left > bounds.right  || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
    }.property(),
});

Component:

​App.LazyImageComponent = Ember.Component.extend(App.InViewportMixin,{
    loadComponent: function() {
        var enteredViewport = this.get('enteredViewport');
        if (enteredViewport == true) {
             console.log(enteredViewport);
        }
    }.observes("enteredViewport").on('didInsertElement')
});

Template:

{{lazy-image}}




Ember BelongsTo within two models issue

Good day all,

Sorry for patience, but have one big trouble with Ember-Data...

I have two models:

  • guild [title, color, players[], owners[], ... ];
  • lessons [title, guild:belongsTo('guild'), ... ];

I want prepare some information for events, in the router (try many another variants) i have next code:

export default Ember.Route.extend({
model() {
    return Ember.RSVP.hash({
        lessons: this.store.findAll('lesson'),
        events: Ember.computed(function(){
            var events = [];
            this.lessons.map(function(lesson){
                events.push({
                    'title': lesson.get('title'),
                    'start': lesson.get('start'),
                    'end'  : lesson.get('end'),
                    'color': lesson.get('guild').get('color') // here i want get color from guild.
                })
            });
            console.log(events);
            return events;
        }).property('lessons')
    });
}});

Another method is compute specific property in the model:

guildColor: Ember.computed('guild', function()....).property('guild')

, also doesn't help :(

Always return UNDEFINED T_T, any help would be appreciate.

Regards, iTux.




Ember loop through an array of checkboxes and get checked items?

I have an Ember.js application (using the Ember CLI). I have a component called sideMenu with the files sideMenu.js and sideMenu.hbs. Within the .js file, I have an array of vehicle names like this:

export default Ember.Component.extend({
    vehicles: ['Audi', 'Chrysler', 'Harley Davidson']
});

In my template for this component, I am looping through these vehicles and creating a checkbox for each item like this:

{{#each vehicles as |vehicle|}}
    {{input type='checkbox' checked='true'}} {{vehicle}}
{{/each}}

This gives me what I want - a few checkboxes with the vehicle names next to it. I want to be able to know what the user unchecked / checked in this list. I tried to do this by creating some Ember properties dynamically and in the template:

{{input type='checkbox' checked="vehicleCheckboxes.{{vehicle}}"}}

This didn't seem to work though. How can I accomplish this? There doesn't seem to be any indication on the Ember documentation that it is possible from within the framework in any way.




Ember 2.2 select relationship/nested

Can someone help with example of related/nested select on ember 2.2? I create component app/components/link-pin-device.js

export default Ember.Component.extend({
  selectedPin:  null,
  actions: {
    selectPin(pin, wdevice) {
      console.log(pin);
      console.log(wdevice);
    }
  }
});

app/templates/components/link-pin-device.hbs

<select value="target.value" onchange={{action "selectPin" "target.value"}}>>
    <option value="">Select...</option>
  {{#each dcPinConfigs as |pinconf|}}
      <option value={{pinconf.id}} selected={{eq selectedPinId pinconf.id}}>{{pinconf.id}}</option>
  {{/each}}
</select>
{{yield}}

app/routes/web-device-module.js

export default Ember.Route.extend({
  model() {
    var self = this;
    return Ember.RSVP.hash({
      webDeviceModules: self.store.findAll('webdevicemodule'),
      dcPinConfigs: self.store.findAll('dcPinConfig').then(function(d){
        let dPin = self.store.peekRecord('dcPinConfig', 2);
        let wMods = self.store.createRecord('webdevicemodule', {
          dcPinLink: dPin,
          name: "sda"
        });
        comment.save();
        return d;
      })
    });
  },
});

How i can change model webdevicemodule.dcPinLink then change value in select?




What is the difference between router and route in Emberjs

What is the difference between router and route in emberjs.I want to know the implimentationable explanation if possible




dimanche 27 décembre 2015

How to reference an element in route?

I was working on an EmberJS application developing.

I defined a route and a template for it

And there is a little button,which id is "myBtn" in that template

I wonder how and when i can reference that button in my route.js

If there is no way,i think i may wrote a single component and wrap it in that route(template),course,element reference in component is clearly and easily

Hope there is a hint for me

Thanks




EmberJS checkbox set value

According to the ember documentation, I can do this:

{{input type="checkbox" name="fruits[]" checked=isAdmin}}

This works fine, however... my checkbox, although 'on or off' but consider the following:

[ ] Apples
[ ] Blueberries
[ ] Oranges

Let's say the 'value' for each one of those is the label... so if someone where to check all 3, it would pass this as an array:

["Apples","Blueberries","Oranges"]

However, this isn't what happens...I get:

["true","true","true"]




Generate Helper handlebars in ember-cli

I have followed the ember guide to create an handlebar helper like in this jsbin

This is the helper

Ember.Handlebars.registerBoundHelper('format-date', function(format, date) {
  return moment(date).format(format);
});

I can successfully reuse in my jsbin but i get an error when i apply the same helper in my application, this is the error Uncaught TypeError: fn.apply is not a function in my helper function , i am not implementing it correctly in my ember-cli

This is the same helper in my application

import Ember from 'ember';

export default Ember.Handlebars.registerBoundHelper('format-date', function(format, date) {
        return moment(date).format(format);
});

What's the problem?

Just to let you know i have generated the ember helper in these steps

1) From command prompt run ember generate helper "format-date"

This was the helper generated

import Ember from 'ember';

export function formatDate(params/*, hash*/) {
  return params;
}

I am definitely mistaking the way i am exporting the format-date helper

How it should be in my ember-cli?




samedi 26 décembre 2015

Failure installing npm dependency specified with full URL

I have created an ember-cli heroku instance:

heroku create xxx-yyy-uuu --buildpack http://ift.tt/1kkWazm

And deployed to it:

git push heroku

But it fails:

remote: bower ember#^2.0.0        invalid-meta ember is missing "ignore" entry in bower.json                                                                                                                 [6/2258]
remote: bower ember#>=1.4         invalid-meta ember is missing "ignore" entry in bower.json
remote: bower ember#> 1.5.0-beta.3     invalid-meta ember is missing "ignore" entry in bower.json
remote: -----> Cleaning up node-gyp and npm artifacts
remote: -----> Building Ember CLI application production distribution
remote: 
remote: Missing npm packages: 
remote: Package: ember-cli-simple-auth-token
remote:   * Specified: git://github.com/jpadilla/ember-cli-simple-auth-token.git
remote:   * Installed: (not installed)
remote: 
remote: Run `npm install` to install missing dependencies.
remote: 
remote: 
remote:  !     Push rejected, failed to compile Ember CLI app
remote: 
remote: Verifying deploy....
remote: 
remote: !       Push rejected to xxx-yyy-uuu.
remote: 
To http://ift.tt/1kkWcaA
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'http://ift.tt/1kkWcaA'

How can the npm package be installed?




Ember addon to add files to root directory

I have an addon which needs to copy a set of JS files from their bower directory to the Ember app's root of /dist (this is for scoping rules associated with service workers). I thought maybe I could use the treeForApp hook but while I'm getting no errors I'm also not getting the desired result.

The index.js is:

const Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ember-upup',
  treeForApp: function(tree) {
    tree = new Funnel(tree, { include: 
      [ 
        'bower_components/upup/dist/upup.min.js',
        'bower_components/upup/dist/upup.sw.min.js' 
      ]});

    return this._super.treeForApp.call(this, tree);
  },




vendredi 25 décembre 2015

EmberJS 2.x , resorting or filtering records from store via actions

Consider the following code in your js file:

App.ApplicationRoute = Ember.Route.extend({
    model: function(){
        return this.store.findAll('team');
    }
});

In your html file, you might have something like this:

{{#each model as |team|}}
<ul>
    <li>{{team.name}}</li>
    <li>{{team.email}}</li>
    <li>{{team.state}}</li>
    <li>{{team.position}}</li>
</ul><br>___<br>
{{/each}}

And the result would be something like

  • Bob Smith
  • bob.smith@bobsmithinc.com
  • NY
  • Leader


  • Jane Smith

  • jane.smith@janesmithinc.com
  • NY
  • Finance


  • John Doe

  • john.doe@janesmithinc.com
  • CA
  • Support

The question is, how would you go about sorting or filter this data after it's displayed? For example, if I want to sort by alphabetical order by name, or email, or lets say I only want to display someone in NY, and not CA.... or maybe type as I search, so if I type 'inc.com'... anyone that has that in their record will show?

My guess is this occurs in the controller via an Action? I just don't understand how to grab the store data (WITHOUT a network request) and resort or filter the data that's already there. I know you can use 'peek', but am unsure how to display the data.




Ember.js and UIKIT

I try to add UIKIT to my Ember.js project

how to do it?

1: bower install --save uikit

All work fine on bower.json

i don't know what to put on ember-cli-build.js

e.g : app.import('bower_components/uikit/css/uikit.css');

How to do about js files?

Thanks




Ember FastBoot Cannot read property 'userAgent' of undefined

I'm trying to use Ember FastBoot for my application but when I run: ember fastboot --serve-assets this error is thrown:

Cannot read property 'userAgent' of undefined TypeError: Cannot read property 'userAgent' of undefined at Object.125.global/document (<anonymous>:121923:53) at s (<anonymous>:104896:621) at <anonymous>:104896:672 at Object.106../big-play-button.js (<anonymous>:113849:23) at s (<anonymous>:104896:621) at <anonymous>:104896:672 at Object.139.../../src/js/utils/merge-options.js (<anonymous>:123824:15) at s (<anonymous>:104896:621) at e (<anonymous>:104896:792) at <anonymous>:104896:810

any help?




How do I update my EmberJS data model in a route after receiving new records via a websocket?

I am using a websocket to receive newly created models in my EmberJS app.

websocket.onMessage((data) => {
  this.store.push(data);
});

This works perfectly as I can confirm using the Ember inspector.

Annoyingly this doesn't update my existing template though. I am showing a list of items using:

model: function(){
  return this.store.findAll("posts");
}

There's a lot of questions like this one on StackOverflow but none seem to answer the real question. Anyone got an idea how this should be fixed?




jeudi 24 décembre 2015

Has somebody seen examples of using of DataTables + Ember with sorting and a pagination on server side?

Has somebody seen examples of using of DataTables + Ember with sorting and a pagination on server side?

I'm trying to master Ember + DataTables. Nothing difficult actually, untill it comes to all sorting and search activities and also when paginations should be on server side.

I.e. we initially load 10 records in DataTables. Then upload records from database on the appropriate action (to sort, replace a page).

Maybe someone has seen an example or tried to realize it?

Or are there any solutions of a pagination, filtering and search for tables?




Component to be notified on route change in EmberJS 2

My task is to develop a menu component for an Ember 2 app. This is going to be a complex component whose visual representation changes as the user goes through routes. For instance it should disable particular menu and all its items when on "/index" route but enable it and some of its items when on "/details" and so on.

So, I've got a component that is passed a singleton model (stored in a Service currently, btw, is it a right place to store globally available singleton models in Ember?). It displays the stuff well but it does not respect the current route nor catches the route changes as user goes through the app. How can I achieve it?

Summing it up:

  1. The component needs to get current route somehow to be able to display its initial state, for instance the user bookmarked the "/details" page and visited it.
  2. The component has to deal with route changes somehow.
  3. Is a Service a good place to hold a singleton model (which could potentially be fetched from server).

Can you provide your thoughts on how to tackle the three above?




mercredi 23 décembre 2015

Store index instead of name in Ember data from ember-paper select box

I'm using a select box component provided by ember-paper (http://ift.tt/1J5K20V).

This is how I've currently got it implemented:

{{#paper-select disabled=disableSelect model=model.fullnameIndex}}
  {{#each columnNames as |name index|}}
    {{#paper-option value=name}}
      {{name}}
    {{/paper-option}}
  {{/each}}
{{/paper-select}}

The columnNames array I'm using to populate the select box contains the following:

["Name", "Address", "City", "State", "Zip", "Email"]

When a selection is made from the select box, the value, in this case name (the first param of the each block), is passed to the fullnameIndex attribute on the model. But what I need to store on the model instead of name is the index (the second param of the each block).

Yes, I could store the index by setting that as the value on the #paper-option instead, but I don't want to do that for two reasons:

  1. When a user makes a selection from the select box, I don't want the value of the box to be a number, but rather show the name of the selection they chose - like how you'd expect a select box to function.
  2. This actually completely breaks anyways, because if you select the first option in the select box (whose index is 0), the select box doesn't show what you chose. It just continues to show the placeholder text.

Any help would be much appreciated. Thanks!




How to update Ember model when data changes

In order to have a dropdown menu that reflects some data in my application, I'm querying the store in the application.js route:

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
      var oldStuff  = this.store.query('stuff', {state: 0});
      var newStuff  = this.store.query('stuff', {state: 1});
      return {oldStuff: oldStuff, newStuff: newStuff};
  }
});

In this way I'm able to iterate on the model in application.hbs and my dropdown looks good, at first.

The problem is that it is static, and only changes if I refresh the page. I'm trying to think how to provide a model that changes when the data changes in the application.

I'm using Ember 1.13




JSON not parsing in Ember with QUnit and Mirage

While unit testing a controller, I ran into an issue where it would alert me that there's been an issue with parsing some JSON. The Gist is located here: http://ift.tt/1TihMbW

I'm not really sure how to debug this.




Computed property that returns a sum of a property on each model

I have a cart model then has items in it that looks something like this

[
    {
        "item_id": 1,
        "item_name":"Item 1",
        "item_price": 500
    },
    {
        "item_id": 2,
        "item_name": "Item 2",
        "item_price": 230
    },
    {
        "item_id": 3,
        "item_name": "Item 3",
        "item_price": 150
    }
]

I need to sum up the item_price property to be able to display it and then pass it along to ember data or an ajax call to complete a purchase.

Not sure if I'm just not understanding the agregate data thing with computeds but I am trying with this

totalDue: Ember.computed.sum('model.@each.item_price')

On the controller but it's returning 0




index.html being loaded as one of my data models

I am using Ember-CLI with Ember 2.2.0 and Ember Data 2.0. This problem was happening before I upgraded my ember-cli to the latest ember.

I have a fairly simple Ember app. There is a 'users' file on my server hard coded for testing with some json of some sample user accounts. http://ift.tt/1qP7lOb

{"users": [{"id":1,"firstName":"Peter","lastName":"blah","email":"blah@example.com","password":"blah","phone":"212-555-1212","isActive":"true"},{"id":2,"firstName":"George","lastName":"blah","email":"blah2@example.com","password":"blah","phone":"310-555-1212","isActive":"true"}]}

On my development machine I have a generated Ember-cli app with the following modifications:

router.js
...
Router.map(function() {
  this.route('users', function() {});
});

...

users.hbs
<h1>Users Route</h1>

<h1>Users Index</h1>
<Table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>

{{#each users as |user|}}
<tr>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
</tr>
{{/each}}

</table>
{{outlet}}

in my routes folder:

user.js
export default Ember.Route.extend({
    model: function() {
        return this.store.findAll('user');
    }
});

Ember throws the following parsing error when it tries to access the users model:

Error while processing route: users.index Unexpected token < SyntaxError: Unexpected token <

I can clearly see in the ember inspector that it is trying to parse my index.html page!! WTH??

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>UserMan</title>
....

Even if I go to the ember inspector, and go to the users route, then try and access the model using the store:

$E.store.findAll('user')

The parsing error happens and its clearly trying to parse the index.html page again.

Any ideas where ember is going wrong? Or what I am doing wrong?




EmberJs "needs" in ember-2.0.1

I am trying to access from a child template to its parent data in the previous versions of emberjs this could have be done using the needs keyword:

app.RepositoriesController = Ember.Controller.extend({
    needs: "user",
    user : Ember.computed.alias("controllers.user");
 });

from what I understand with the new ember version this should be done like the following (as the needs keywords became deprecated):

app.RepositoriesController = Ember.Controller.extend({
    user: Ember.inject.controller('user')
});

but it doesn't seems to work in my html code I use the following line which is blank:

{{user.name}}

Thanks!




Using pure Ember to create SVG chart with transition effect

I'm trying approach in this link D3 and React - the future of charting components? to create some charting components without using d3 to generate svg elements.

Now I could do the most simplest case: if I have an array [1, 1, 1], I will get a series of bars with height equal to 1. When I change the array to [2, 2, 2], I get a series of new bars with height equal to 2 instantly.

What I want to have is, when I change data array, the bar could change height with an animation effect. For the above input, the second time height of each bar would grow from 1 to 2.

Inside my component I use each to iterate through values

{{#my-svg}}
  {{#each values as |v|}}
    {{my-rect height=v ........}}   // my own component
  {{/each}}
{{/my-svg}

It looks like Ember will destroy and recreate all rects instead of change their height property. Therefore my css transition property no longer works. (It works if I only have one <rect>)

Another way in my mind is adding oldHeight newHeight for each bar, use other jquery library to change height with transition based on those two values. But if that so I need to run this function for every bar, which sounds very slow. I'm wondering is there any better to achieve it.




Dynamically Set two images in wrapper

I have created an ember app.The app contains a feed page and is constituted with images.There are two images sides by sides inside a wrapper of dimension ( 700x416 ).Now I want to implement something in which the two images set themselves dynamically based upon their original size ( this means the images with greater dimension will acquire more space in wrapper than the second images.How do I implement it.I am very new to frontend part and not sure where to start.Please answer with demos or tutorial link for my better understanding




mardi 22 décembre 2015

How to make a Image card and make it appear it on same page

I am very new to frontend part.I have created an ember app which has a feed page.The feed page is mainly consisted of images and its like,comment.Now what I want is when I click on images it should open the original size image and its likes and comment (Very much similar to facebook page,when you click on images.It open a new window or card in which all information about it present).Same is the case with Pinterest.How do I achieve it.Now very sure where look or start.Please give some example and demo for better understanding of me.




Ember search in current model

This code for search in hasMany childrens work like a charm. But i want search in current model (e.g. filtered by store name: 'storeOne'), that is reason because i want search in current model, not query to this.store and not query to api...

        var _self = this;
        this.store.findAll('store').then(function(stores){

            // search
            var promises = stores.map(function(store){

                return Ember.RSVP.hash({
                    store: store,
                    customers: store.get('customers').then(function(customers){
                        return customers.filter(function(customer){
                            var regExp = new RegExp(search, 'i');

                            var retVal = false;

                            if (customer.get('name') !== undefined ) retVal = retVal || customer.get('name').match(regExp);
                            if (customer.get('surname') !== undefined ) retVal = retVal || customer.get('surname').match(regExp);
                            if (customer.get('age') !== undefined ) retVal = retVal || customer.get('age').match(regExp);

                            return retVal;
                        });
                    })
                });

            });

            Ember.RSVP.all(promises).then(function(filteredData){
                _self.set('content', filteredData);
            });
        });

  • Question: How can i filter by search customers in current model without use findAll or query to API ?



Using components instead controllers in EmberJS v2

I am beginner in EmberJS. I have made todomvc for ember v2 for learning Ember.

My implementation works without controller. I use components instead controllers. Because in documentation I see

Controllers are very much like components, so much so that in future versions of Ember, controllers will be replaced entirely with components.

But I think it is some ugly solution. Now I will explain why.

This is template for todo item component for my todolist app/templates/components/todo-item.hbs:

<li class="{{if isCompleted 'completed'}} {{if isEditing 'editing'}}">
    {{#if isEditing}}
        {{input-focused class="edit" value=item.title focus-out="acceptChanges" insert-newline="acceptChanges"}}
    {{else}}
      {{input type="checkbox" checked=isCompleted class="toggle"}}
      <label {{action "editTodo" on="doubleClick"}}>{{item.title}}</label><button {{action "removeTodo"}} class="destroy"></button>
    {{/if}}
</li>

It has acceptChanges and removeTodo events. And in js part of component I have handlers:

//app/components/todo-item.js
import Ember from 'ember';

export default Ember.Component.extend({

    updateTodoAction: 'updateTodo',
    deleteTodoAction: 'deleteTodo',

    isEditing: false,

    // some lines removed for brevity

    actions: {
      editTodo: function() {
        this.set('isEditing', true);
      },

      acceptChanges: function() {
        this.set('isEditing', false);
        this.sendAction('updateTodoAction', this.get('item'), this.get('item.title'));
      },

      removeTodo: function () {
        this.sendAction('deleteTodoAction', this.get('item'));
      }
    }
});

In js code of component I don't work with storage. I send this.sendAction(), and my route will handle it. And todos-route works with storage. Please look at todos route:

// app/routes/todos.js
import Ember from 'ember';

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

    actions: {
        // some lines removed from here for brevity

        updateTodo: function(todo, title) {
            if (Ember.isEmpty(title)) {
                this.send('deleteTodo', todo);
            } else {
                todo.save();
            }
        },

        deleteTodo: function(todo) {
            todo.deleteRecord();
            todo.save();
        },

       // some lines removed from here for brevity
    }
});

When user clicks on remove button, it generates removeTodo action and it will handled in removeTodo() in js part of component. And then removeTodo() function calls this.sendAction('deleteTodoAction' ... ), which generates deleteTodo action. This action will handled in todos route in deleteTodo() method. I have todo.save() in this method.

The acceptChanges action works much like removeTodo, but it sets property isEditing = false before calling this.sendAction.

I have following chain for actions

component template -> component js -> route

I think for deleteTodo() will be better to exclude component js part. But how? In updateTodo() I need component js part, because I set value for isEditing property. But for calling route I need updateTodoAction property. And it is ugly for me. Can it work without updateTodoAction property? How?

Also I'd like to see any your comments about my solution (components instead controllers) or any part of my code.

Thank you, friends!




Does not work location history in embedded application: ember js

I have a large application in which want implement a part of the functional on Ember js. There is some page which is located on this path /item/item_id_here/profile/documents Only documents must be Ember app. I create new ember project with ember cli. And include to documents page in my base project vendor.js and ember.js where router is:

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

const Router = Ember.Router.extend({
});

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

Router.reopen({
    location: 'history'
});


export default Router;

When I run the application in the console displays an error

UnrecognizedURLError: /item/item_id_here/profile/documents

When i try change:

Router.reopen({
    location: 'hash'
});

Everything works well.

I'm a little worked with Ember so I started to think that my situation is normal. But I decided to double-check and include ember to my basic project directly without ember cli etc. For example:

window.App = Ember.Application.create({
    rootElement: '#ember-app'
});

App.Router.reopen({
    location: 'history'
});


App.Router.map(function() {
    this.route('test');
});

App.IndexRoute = Ember.Route.extend({
    model: function() {
       alert( 'index' ); 
    }
});

App.TestRoute = Ember.Route.extend({
    model: function() {
        alert( 'test' );
    }
});

I was discouraged but everything worked as it should




How to implement Command Pattern instead of using Adapter?

I'm new to EmberJS and a bit lost. I would like to ask some advice to get started correctly.

We have a SaaS which is not built with EmberJS. I'm trying to refactor a part of it and use EmberJS for that.

Our Software implements the command pattern. It means we send action (JSON object) to the server to create, update and delete (also undo/redo) our model objects.

I can't really use Adapter for that because they seam to be created for REST Interface, but we are not using REST for that part.




Ember-cil uses wrong path for jquery and qunit

I'm using a fresh install of ember-cli with the following versions:

~/Projects/ember_tut > ember s
version: 1.13.13
node: 4.2.1
npm: 2.14.10
os: darwin x64

Immediately after running ember new ember_test:

~/Projects/ember_tut > ember s
version: 1.13.13
Livereload server on http://localhost:49154
Serving on http://localhost:4200/
ENOENT: no such file or directory, stat '/Users/sms/Projects/ember_tut/tmp/concat_with_maps-input_base_path-http://ift.tt/1MtMhWL'
Error: ENOENT: no such file or directory, stat '/Users/sms/Projects/ember_tut/tmp/concat_with_maps-input_base_path-http://ift.tt/1MtMhWL'
    at Error (native)
    at Object.fs.statSync (fs.js:849:18)
    at ConcatWithMaps.keyForFile (/Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/index.js:90:20)
    at Array.map (native)
    at ConcatWithMaps.CachingWriter._conditionalBuild (/Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/index.js:112:65)
    at /Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/node_modules/broccoli-plugin/read_compat.js:61:34
    at lib$rsvp$$internal$$tryCatch (/Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:493:16)
    at lib$rsvp$$internal$$invokeCallback (/Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:505:17)
    at lib$rsvp$$internal$$publish (/Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:476:11)
    at lib$rsvp$asap$$flush (/Users/sms/Projects/ember_tut/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1198:9)

It's looking for jquery.js in bower_components/jquery/dist/jquery.js but it's really in bower_components/jquery/jquery-1.11.3/dist/jquery.js.

This is easily "fixed" by creating a symlink in bower_components/jquery/ to bower_components/jquery/jquery-1.11.3/dist, but that's awfully klunky, and I'm wondering what the right way to address it is.




ember-simple-auth with devise session lost on refresh

I used simplabs ember-simple-auth in ember and have rails setup using devise. when authenticate() gets called it sends the email and password to rails. which returns the token. I can see token in localstorage as follows but as soon as I hit refresh the data is lost taking me back to login page.

{"secure":{
    "authenticator":"authenticator:devise",
    "id":1,"email":"abc@abc.com",
    "created_at":"2015-12-21T06:25:31.000Z",
    "updated_at":"2015-12-22T10:11:56.728Z",
    "authentication_token":"UoUTuVmUfwsVUnHVkE4U",
    }
}

in my authenticate() function I have setup devise as authenticator with credentials.

export default Ember.Controller.extend({
  _email: Ember.inject.controller('email'),
  session: Ember.inject.service('session'),
  actions: {
    authenticate(){
      let identification = this.get('_email.email');
      let password = this.get('password');

      console.log(identification, password);
      this.get('session').authenticate("authenticator:devise",identification,password).catch((reason)=>{
        this.set('errorMessage',reason.error|| reason);
      });
    }
  }
});

inside my authenticators folder I have defined devise.js which contains

import DeviseAuthenticator from 'ember-simple-auth/authenticators/devise';
export default DeviseAuthenticator.extend();

inside my authorizers folder I have defined devise.js which contains

import DeviseAuthorizer from 'ember-simple-auth/authorizers/devise';
export default DeviseAuthorizer.extend();

my config/environment.js contains

ENV['simple-auth']={
    authorizer: 'simple-auth-authorizer:devise'
  };
  ENV['simple-auth-devise']={
    identificationAttributeName: 'email',
    resourceName:'user',
    tokenAttributeName: 'authentication_token'
  };

according to Ember Simple Auth: Session lost on refresh specifying identificationAttributeName: 'email' should have solved the problem but it still persists. Rails side

application_controller.rb

class ApplicationController < ActionController::Base
  respond_to :json
  protect_from_forgery with: :null_session
  before_filter :authenticate_user_from_token!

  private
  def authenticate_user_from_token!
    authenticate_with_http_token do |token, options|
      user_email = options[:email].presence
      user = user_email && User.find_by_email(user_email)
      if user && Devise.secure_compare(user.authentication_token, token)
        sign_in user, store: false
      end
    end
  end
end

and session_controller.rb :

class SessionsController < Devise::SessionsController
  def create
    respond_to do |format|
      format.html { super }
      format.json do
        self.resource = warden.authenticate!(auth_options)
        sign_in(resource_name, resource)
        data = {
          token: self.resource.authentication_token,
          email: self.resource.email
        }
        render json: data, status: 201
      end
    end
  end
end

routes are configured to use the session controller. I just started emberjs and I am getting stuck on this for some days now.I dont know where I have missed somthing.




How to serialize embedded related data in PUT-Request in ember-data

I am sending and returning data from ember-data to my RESTService like this:

{
    "posten":{
        "id":4711,
        "name":"Mein Posten",
        "postenaufteilung":[{id:1,name...},...]        
    }
}

The serializer is configured for embedded data:

attrs: {
    postenaufteilung: {
        embedded: 'always',
        serialize: 'postenaufteilung'
    }
},

To send data to my RESTService in the correct way, I need to serialize the data:

serializeIntoHash: function (data, type, record, options) {
    //Ember.merge(data, this.serialize(record, options));        
    var root = Ember.String.decamelize(type.modelName),
    serialized = this.serialize(record, options);
    data[root] = serialized;
    data.posten["postenaufteilung"] = [];
    record.hasMany('postenaufteilung').forEach(function (postenaufteilungsitem) {
        paSerialisiert = postenaufteilungsitem.serialize();
        if (Em.isNone(paSerialisiert.posten)) {
            paSerialisiert.posten = 0;
        }
        data.posten.postenaufteilung.push(paSerialisiert);
    });
},

Everything works as expected, only when I save my model and ember-data sends a PUT, the returned embedded model (postenaufteilung) is not refreshing the model inside the store.

Am I missing something here?




ember 2.2.0 this.store.queryRecord returns Error: Adapter operation failed at new Error (native) at Error.EmberError

I am using ember 2.2.0 with ember-pouch, so my problem is that I am trying to retrieve data from the store by param different than id here is my code:

this.store.queryRecord('facility', { api_number: '42-001-1234'})

and it fails it following error:

GET http://localhost:4200/facilities?api_number=42-001-1234 404 (Not Found) send @ jquery.js:9664jQuery.extend.ajax @ jquery.js:9215(anonymous function) @ rest-adapter.js:764initializePromise @ ember.debug.js:52308Promise @ ember.debug.js:54158ember$data$lib$system$adapter$$default.extend.ajax @ rest-adapter.js:729ember$data$lib$system$adapter$$default.extend.queryRecord @ rest-adapter.js:404ember$data$lib$system$store$finders$$_queryRecord @ finders.js:168ember$data$lib$system$store$$Service.extend.queryRecord @ store.js:897chooseFacility @ facility.js:16_emberMetalMixin.Mixin.create.send @ ember.debug.js:31366runRegisteredAction @ ember.debug.js:28471Backburner.run @ ember.debug.js:681run @ ember.debug.js:20105actions.push.handler @ ember.debug.js:28465(anonymous function) @ ember.debug.js:43052jQuery.event.dispatch @ jquery.js:4670elemData.handle @ jquery.js:4338 ember.debug.js:30877 Error: Adapter operation failed at new Error (native) at Error.EmberError (http://localhost:4200/assets/vendor.js:26414:21) at Error.ember$data$lib$adapters$errors$$AdapterError (http://localhost:4200/assets/vendor.js:67497:50) at ember$data$lib$system$adapter$$default.extend.handleResponse (http://localhost:4200/assets/vendor.js:68801:16) at hash.error (http://localhost:4200/assets/vendor.js:68881:33) at fire (http://localhost:4200/assets/vendor.js:3350:30) at Object.self.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3462:7) at done (http://localhost:4200/assets/vendor.js:9518:14) at XMLHttpRequest.callback (http://localhost:4200/assets/vendor.js:9920:8)onerrorDefault @ ember.debug.js:30877exports.default.trigger @ ember.debug.js:52928(anonymous function) @ ember.debug.js:54177Queue.invoke @ ember.debug.js:320Queue.flush @ ember.debug.js:384DeferredActionQueues.flush @ ember.debug.js:185Backburner.end @ ember.debug.js:563Backburner.run @ ember.debug.js:685run @ ember.debug.js:20105hash.error @ rest-adapter.js:761fire @ jquery.js:3148self.fireWith @ jquery.js:3260done @ jquery.js:9316callback @ jquery.js:9718




lundi 21 décembre 2015

What do you think about my todovmc for emberjs v2

I have made todomvc for ember v2 http://ift.tt/1IlZztl

I am beginner in EmberJS. I need your opinions about this application.

May be you will find some bad solutions.

My implementation works without controller. I use components instead controllers. Because in documentation I see

Controllers are very much like components, so much so that in future versions of Ember, controllers will be replaced entirely with components.

I'd like to see your comments about this solution.

Thank you, friends!




Kendo ui nested row and column grid implementation

enter image description here Can any body suggest the json format and grid implementation for the attached format.




(Updated) Running 'ember s' and opening up the page shows the page stuck on loading

Updated: Deleted and reposted question because I needed to delete something personal without it showing in the edits.

I stopped working on ember projects for about a week, and I think I changed a setting or version of something to make it stop working. The project is working on my co-worker's computer so it must be something I'm using. Here are files I'm using that I think are relevant:

bower.json

{
  "name": "fakeprojectname",
  "dependencies": {
    "ember": "1.13.3",
    "ember-cli-shims": "ember-cli/ember-cli-shims#0.0.3",
    "ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
    "ember-data": "1.13.5",
    "ember-load-initializers": "ember-cli/ember-load-initializers#0.1.5",
    "ember-qunit": "0.4.1",
    "ember-qunit-notifications": "0.0.7",
    "ember-resolver": "~0.1.18",
    "jquery": "^1.11.1",
    "loader.js": "ember-cli/loader.js#3.2.0",
    "qunit": "~1.17.1",
    "font-awesome": "~4.4.0"
  }
}

package.json

{
  "name": "fakeprojectname",
  "version": "0.0.0",
  "description": "Small description for fakeprojectname goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "start": "ember server",
    "build": "ember build",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.0.2",
    "ember-cli": "^1.13.1",
    "ember-cli-app-version": "0.4.0",
    "ember-cli-babel": "^5.0.0",
    "ember-cli-coffeescript": "0.11.0",
    "ember-cli-compass-compiler": "0.0.18",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "^1.0.0",
    "ember-cli-font-awesome": "0.1.1",
    "ember-cli-htmlbars": "0.7.9",
    "ember-cli-htmlbars-inline-precompile": "^0.1.1",
    "ember-cli-ic-ajax": "0.2.1",
    "ember-cli-inject-live-reload": "^1.3.0",
    "ember-cli-qunit": "0.3.15",
    "ember-cli-release": "0.2.3",
    "ember-cli-uglify": "^1.0.1",
    "ember-data": "1.13.5",
    "ember-disable-proxy-controllers": "^1.0.0",
    "ember-export-application-global": "^1.0.2"
  }
}

When running ember -v (My coworker has the same output)

version: 1.13.1
node: 0.12.7
npm: 2.12.1

Any help is appreciated. Thank you for your time.




Get promise is not being met with a Then function

I'm having some issues with my first emberjs application. It is a sample application that contains users and notes for each user that they can update. I'm trying to do unit tests right now, so that I know the format for accessing information from the store, but I'm getting some errors when I try to access the notes from the user model. Here is the code:

testUser.get("notes").then(notes => {
   assert.equal(notes[0], testNote, "Note is valid."); 
});

And here is the error:

testUser.get(...).then is not a function

From what I read on emberjs.com the .get(...) function returns a promise that can then be used with a .then for access different elements in the array. Where am I going wrong?




Running 'ember s' and opening up the page shows the page stuck on loading

I stopped working on ember projects for about a week, and I think I changed a setting or version of something to make it stop working. The project is working on my coworker's computer so it must be something I'm using. Here are files I'm using that I think are relevant:

bower.json

{
  "name": "fakeprojectname",
  "dependencies": {
    "ember": "1.13.3",
    "ember-cli-shims": "ember-cli/ember-cli-shims#0.0.3",
    "ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
    "ember-data": "1.13.5",
    "ember-load-initializers": "ember-cli/ember-load-initializers#0.1.5",
    "ember-qunit": "0.4.1",
    "ember-qunit-notifications": "0.0.7",
    "ember-resolver": "~0.1.18",
    "jquery": "^1.11.1",
    "loader.js": "ember-cli/loader.js#3.2.0",
    "qunit": "~1.17.1",
    "font-awesome": "~4.4.0"
  }
}

package.json

{
  "name": "fakeprojectname",
  "version": "0.0.0",
  "description": "Small description for ometria goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "start": "ember server",
    "build": "ember build",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.0.2",
    "ember-cli": "^1.13.1",
    "ember-cli-app-version": "0.4.0",
    "ember-cli-babel": "^5.0.0",
    "ember-cli-coffeescript": "0.11.0",
    "ember-cli-compass-compiler": "0.0.18",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "^1.0.0",
    "ember-cli-font-awesome": "0.1.1",
    "ember-cli-htmlbars": "0.7.9",
    "ember-cli-htmlbars-inline-precompile": "^0.1.1",
    "ember-cli-ic-ajax": "0.2.1",
    "ember-cli-inject-live-reload": "^1.3.0",
    "ember-cli-qunit": "0.3.15",
    "ember-cli-release": "0.2.3",
    "ember-cli-uglify": "^1.0.1",
    "ember-data": "1.13.5",
    "ember-disable-proxy-controllers": "^1.0.0",
    "ember-export-application-global": "^1.0.2"
  }
}

When running ember -v (My coworker has the same output)

version: 1.13.1
node: 0.12.7
npm: 2.12.1

Any help is appreciated. Thank you for your time.




display url with different value from what you put in search box ember

I have a search box on admin page admin.hbs like this:

{{input value=search class="wide input" placeholder="Inquiry ID or User Email"}}
<div class="medium info btn" {{action 'search' search}}><button {{bind-attr class="isLoading:loading"}} >Search</button></div>

In the admin_controller.js, the search action looks like this:

search: function(search){
    if (!this.get('isLoading')){
        this.set('isLoading', true);
        if(search.indexOf('@') == -1){
            this.transitionToRoute('inquiry', search);
        } else {
            this.transitionToRoute('user', search);
        }
        this.set('isLoading', false);
      }
}

This function check whether the input is inquiry id or user email, and then transition to different route in order to get the right data. My issue is with the user search so I'll just show codes relates to user search. Here is the router.js:

App.Router.map(function(){
  this.resource("inquiry", {path: "inquiry/:inquiry_id"});
  this.route("user", {path: "user/:email"});
});

This is the user_route.js:

App.UserRoute = Ember.Route.extend({
  queryParams: {
    email: {
        refresh: true,
    }
  },
  model: function(params){
    return this.store.find('user', {email: params.email}).then(function(users{
        if (users){
            return users.get('firstObject');
        }
    });
  },
  setupController: function(controller, model){
    this._super(controller, model);
    controller.set('isLoading', false);
  }
});

Currently the url is always like: ../admin/user/test1@gmail.com I want it to be like: ../admin/user/1 I mean instead of showing the email I put in the search box, I want the url to show the user id, which is also a property in user model. I have a solution now: grab the user model in admin_controller.js depend on the user email. Then get the user id and pass the model to user_route.js. But I don't know how to get the user model in admin_controller.js. Could someone give me a clue?




Reusing some existing AngularJS functionality inside of an EmberJS app

I am in the middle of writing an app using AngularJS. Part of the app is visualization of some data. Currently, to get that done, I am using a simple layout algorithm that I wrote myself to basically output divs with absolute positioning.

There is another team that would like to use this visualization in their app, but their app is written in EmberJS. They don't care nor need my code for routing, etc.

The question I have is this... Is it possible for them to take what I have and integrate it into their EmberJS app. They would obviously not take the code for routing... but can they take my services and controller and fairly easily integrate that into one of their views?

Any guidance on this would be appreciated.

Thank you!




Detect a change in the dynamic segment

I have an authenticated route with a dynamic segment :slug that is used as separate organizations' short names. Within each organization there are individuals and groups. It's possible that different organizations will have the same individual IDs and group IDs.

So the URLs /bigcompany/s/individual/1 and /smallcompany/s/individual/1 are both valid and will take you to the individual with ID=1 for each of those companies.

router.js

Router.map(function() {
    this.route('authenticated', { path: '/:slug' }, function() {
        this.resource('individual',  { path: 's/individual/:id' }, function() {
            ...
        });
        this.resource('groups', { path: 's/groups' }, function() {
            this.route('group', { path: ':id' });
        });
    });

    this.route('login', { path: ':slug/s/login' });
});

After I log in from /bigcompany/s/login, it takes me to /bigcompany/s/individual/1 and loads the model for that individual.

The problem is that I can directly change the URL in the browser from bigcompany to smallcompany and it will go ahead and load the model for /smallcompany/s/individual/1.

Is there a way that if a user directly edits the URL in the browser to a different :slug that it will log the user out of the original :slug and load the login page for the new :slug?




Printing Ember.js page : templates not displaying

When I try to print my Ember.js page application, templates aren't displayed on the sheet (it only displays a big empty white section). Any explanations or solutions?

Thank you




{{link-to}} within a model's attribute?

Given something like a post model with a body attribute, is there a way to get ember to dynamically render {{link-to}}'s within the body attribute?

Example:

// The model
post = {
  body: `
    {{#link-to "posts.index"}}
      <h1>The "{{#link-to}}" is rendered literally!</h1>
    {{/link-to}}`
}

// The .hbs file
<div class="container">
  {{postBody post.body}}
</div>

// Helper function to avoid escaping the HTML
export function postBody(postBody) {
  return Ember.String.htmlSafe(postBody);
}
export default Ember.Helper.helper(postBody);

The only thing I can think to do is enter a static link, which would cause a full page reload.




EmberJS, How access in a child template to the model in the parent controller

I have this router:

// app/router.js
Router.map(function() {
  this.route('battle', function(){
    this.route('combats');
  })
});

In the combats route I can access to the battle model easily using:

// app/routes/battle/combat.js
this.modelFor('battle');

But if I want to access to this model also in the combats template things start to be complicate:

// app/templates/battle/combats.hbs
<h1>Combats for Battle {{<how to access to the battle>.title}}</h1>

{{#each model as |combat|}}
  {{combat.date}}
{{/each}}

I have solved this sending properties to the combats Controller from the combats Route:

// app/routes/battle/combat.js
setupController: function(controller, model) {
  controller.set('content', model);
  controller.set('battle', this.modelFor('battle'));
}

But I don't know if it is the correct way, it looks too much indirect under my perspective, like that you have to make a long workaround to make this property available in the template.




EmberJS, How to import files using root path?

I have this a model in this path:

/my-project/app/models/my-model.js

And I want to import it from a route in this path:

/my-project/app/routes/battles/battle/combats/new.js

The import sentence looks like this:

import MyModel from '../../../../models/my-model';

The path is insane, I have to use the try and error system to figure out it. Also if I want to import the same model in another component I can't just copy&paste because this path is only valid from an specific path. For the same reason if I change the path of the component importing my model I have to update the import path.

I would like to have path relative to the root of the project, something like:

import MyModel from '/models/my-model';

Is this possible?




EmberJS, How to NOT render the parent View

I have this router:

// app/router.js
Router.map(function() {
  this.route('battles', function(){
    this.route('battle', { path: ':id' }, function(){
      this.route('combats', function() {
        this.route('new');
      });
    });
  });
});

And these templates:

  // app/templates/battles.hbs
  {{#each model as |battle|}}
    {{battle.name}}
  {{/each}}
  {{outlet}}

  // app/templates/battles/battle/combats.hbs
  {{#each model as |combat|}}
    {{combat.date}}
  {{/each}}

  // app/templates/battles/battle/combats/new.hbs
  {{input type="text" value=date}}
  <button {{action "createCombat"}}>Create Combat</button>

So This is what is rendered for each route

  route: /battles
  -> app/templates/battles.hbs

  route: /battles/B2/combats
  -> app/templates/battles.hbs
  -> app/templates/battles/battle/combats.hbs

  route: /battles/B2/combats/new
  -> app/templates/battles.hbs
  -> app/templates/battles/battle/combats.hbs

So for the route /battles/B2/combats/new the template app/templates/battles/battle/combats/new.hbs is not rendered. This has a quick fix:

  // app/templates/battles/battle/combats.hbs
  {{#each model as |combat|}}
    {{combat.date}}
  {{/each}}
  {{outlet}}

But then the route renders this:

  route: /battles/B2/combats/new
  -> app/templates/battles.hbs
  -> app/templates/battles/battle/combats.hbs
  -> app/templates/battles/battle/combats/new.hbs

And I don't want the list of combats to be rendered when I'm rendering the combat/new form. I would like this:

  route: /battles/B2/combats/new
  -> app/templates/battles.hbs
  -> app/templates/battles/battle/combats/new.hbs

How I can create this setup?




In an Ember route how can I check if an action exists?

In a component it is really easy to have an optional action provided to the component. In the JS of the component I can write:

if (this.get('someAction')) {
  this.sendAction('someAction');
}

In my application route I have a 'generic action' that saves me providing widget components with long lists of actions, it looks like this:

genericAction: function(customActionName, customActionParams) {
  this.send(customActionName, customActionParams);
}

For various reasons (including using genericAction in some components to fire an action a test could subscribe to, but the app not necessarily use in some hard to test async/pretender workflows) I would prefer to check the action exists, i.e:

genericAction: function(customActionName, customActionParams) {
  if (this.get(customActionName)) {
    this.send(customActionName, customActionParams);
  }
}

Similar to how you can in a component, however this does not work, nor does this.controller.get(customActionName).

Other than keeping a hard coded list of actions, how can I achieve this?




dimanche 20 décembre 2015

How to make Ember computed array based on DS.hasMany property update when a new record is created?

DEBUG: -------------------------------
DEBUG: Ember             : 2.2.0
DEBUG: Ember Data        : 2.1.0
DEBUG: jQuery            : 2.1.4
DEBUG: Model Fragments   : 2.0.0
DEBUG: Ember Simple Auth : 1.0.0
DEBUG: -------------------------------

My model has a computed property upcomingReminders that filters and sorts the DS.hasMany property, reminders.

# app/models/job.js
import Ember from 'ember';
import DS from 'ember-data';

export default DS.Model.extend({
  // ...
  reminders: DS.hasMany( 'reminder', { "async": true } ),
  undoneReminders: Ember.computed.filterBy('reminders', 'done', false),
  upcomingReminders: Ember.computed.sort('undoneReminders', 'undoneSorting')
});

I create a new record in the route like so:

# app/routes/dashboard/jobs/show/reminders/new.js
import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    let newRecord = this.get('store').createRecord( 'reminder' , { 
      target: this.modelFor("dashboard.jobs.show")
    });
    return newRecord;
  }
});

And then save it from the controller like so:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    save() {
      this.get('model').save().then( (model) => {
        let target = model.get('target');
        this.transitionToRoute('dashboard.jobs.show.reminders', target );
      });
    }
  }
});

The template looks like this:

<div class="valign-wrapper right">
  {{#link-to "dashboard.jobs.show.reminders.new" model class="right"}}
    {{md-btn text="Add Reminder" icon='mdi-content-add' class='green'}}
  {{/link-to}}
</div>

{{#each model.upcomingReminders as |reminder|}}
  {{reminder-widget reminder=reminder}}
{{else}}
  There are no upcoming reminders
{{/each}}

{{outlet}}

When I save the model, it won't show up in the list until I refresh the page, although it will show up in a list of all reminders immediately, and shows up in the list if I change the each block to iterate over model.reminders (the raw DS.hasMany property, as opposed to the sorted & filtered property). Even if I navigate to a route with a list of all reminders, and then return, it won't be there 'til after a refresh.

So how can I trigger a rerender of this computed property?




ember how to add multiple models

I have one model eg 'reader' and I want to add multiple 'books' model to this object.

reader model defined books field like this:

bookss: DS.hasMany('book', {async: true}), 

when i create reader I want to add some book models to it. in template, I can list books like this:

{{#each books as |book index|}}
    {{book.name}}, {{index}} <br>
{{/each}}

<button {{action 'addReader'}}>add</button><br>

how can I pass books to 'addReader' function?




How to populate ember-cli-jstree with model data

I am trying to use this addon to create a tree from my data. I can successfully create a tree from the examples provided in the test/dummy in github, but when I try to use data from a model it seems to be expecting json data and not the ember model.

// models/user.js 
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  children: DS.hasMany('user', {inverse: 'parent', async: true}),
  parent: DS.belongsTo('user', {inverse: 'children', async: true})
});

// routes/users.js
import Ember from 'ember';

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

// templates/users.hbs    
<h2>Users</h2>
<div class="sample-tree">
   {{ember-jstree
      data= model
   }}
</div>

I have searched for a working example but so far have not found one.




view object properties is not resetting on re-render of view in ember js

view variable is resetting on re-render of view but view object property not resetting on re-render of view

    App.FooviewView = Ember.View.extend({
        flag1:false,
        obj:{flag:false},
        actions:{
            test:function(){
                this.set('flag1',true)
                this.set('obj.flag1',true)
            }
        }
    })

on render of view flag1 is resetting to false but obj.flag is remains true. why is like that... help pls.




Change the image when clicked on it in ember

I a new to ember and trying to figure out a solution.I have a template which contains images.When I click on the images it should change the image.

applicaton.hbs

      <a href {{action "change"}}>
      <img src = "follow.png" /></a>

Controller.js

actions:{
    change() {
    src:"unfollow.png"
    },

How do I change the img tag source from "follow.png" to "unfollow" and vice-versa when I click on it.




samedi 19 décembre 2015

Ember-cli default integration tests always fail with parse error

The default integration tests in ember-cli always fail with an error of "Parse error". For example if I have a default integration test like so:

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

moduleForComponent('campfire-video', 'Integration | Component | campfire video', {
  integration: true
});

test('it renders', function(assert) {
  assert.expect(2);

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{campfire-video}}`);

  assert.equal(this.$().text(), '');

  // Template block usage:
  this.render(hbs`
    {{#campfire-video}}
      template block text
    {{/campfire-video}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});

where the component has no template file and the JS looks like the following:

export default Ember.Component.extend({
  attributeBindings: ['autoplay', 'controls', 'loop', 'muted', 'poster', 'src'],
  classNames: ['campfire', 'video'],
  tagName: 'video'
});

I will always get this error. I have tried upgrading ember-cli-htmlbars-inline-precompile but it does not fix the error. Is there anything I am doing wrong or is there a problem with ember-cli?




Ember.js adapter/serializer configuration for legacy API

I am trying to get a new Ember 2.2 application to talk to a legacy API server. I can not change server code so trying to figure out how to customise Ember Data to handle the models well.

The issue is that server APIs return a JSON like this for every kind of models:

{ content: [ {id: 1, title: "a"}, {id: 2, title: "b"}, meta: {...} ]

I would use JSONAPISerializer if the server used a different root for each model instead of the content key. I would use JSONSerializer if the response was just a plain array (i.e. no content key in it at all). But I do not see a way to get it to work with the response above.

What would be your suggestion?




Avoid ember to wrap my component

This is my component:

{{#link-to routeName class="list-group-item"}}
  <i class="fa {{icon}} fa-fw"></i>&nbsp; {{text}}
{{/link-to}}

Which I use:

<div class="list-group">
  {{icon-link routeName="my-account" icon="fa-user" text="Personal details"}}
...
</div>

The expected html is:

<div class="list-group">
  <a class="list-group-item" href="xxx">
    <i class="fa fa-user fa-fw"></i>&nbsp; Personal details
  </a>
...
</div>

But because ember wraps the components in a div, the bootstrap rules do not apply anymore and the list-group has a wrong style.

If I change the component tag to a, and remove link-to from the component template, I loose the flexibility of link-to - and I do not know how to set attributes (href, class) in the containing tag.

It seems I can not use an Ember component for this then? Or is there a way to tellink ember no to wrap my component in a div, or anything else really: in order for the CSS to work, the markup structure must not be modified.




vendredi 18 décembre 2015

No Tests Running with Ember CLI

I've setup a model that I would like to unit test in Ember but every time I run the test suite, no matter what I do, I get 0 tests ran.

$ ember test
version: 1.13.1
Built project successfully. Stored in "/Users/BenAMorgan/Sites/frontend/tmp/class-tests_dist-pjaTeNtp.tmp".

1..0
# tests 0
# pass  0
# fail  0

# ok
No tests were run, please check whether any errors occurred in the page (ember test --server) and ensure that you have a test launcher (e.g. PhantomJS) enabled.

The model:

// app/models/feature.js
import DS from 'ember-data';

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

What the test looks like:

// tests/unit/models/feature-test.js
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('feature', 'Unit | Model | feature', {
  // Specify the other units that are required for this test.
  needs: []
});

test('it exists', function(assert) {
  var model = this.subject();
  // var store = this.store();
  assert.ok(!!model);
});

All the npm dependencies installed without errors. Testem is installed. PhantomJS is installed via npm. Not sure where I'm going wrong.




how to add a class via binding in ember 2.0

I have a bootstrap button group in my Ember 2.2 app that looks like this:

 <div class='btn-group' role='group' aria-label='...'>
     <button type="button" class="btn btn-primary btn-xsm active={{aIsActive}}" >A</button>
     <button type="button" class="btn btn-primary btn-xsm active={{bIsActive}}" >B</button>
     <button type="button" class="btn btn-primary btn-xsm active={{cIsActive}}" >C</button>
</div>

'aIsActive', 'bIsActive', and 'cIsActive' are defined in the associated controller, and only one will be 'true' at a given time. The syntax shown above doesn't work. What's the proper way of doing this?




ember-cli-mirage testing request params

I have default params that are added to the search request from a route. I would like to test these in ember-cli-mirage but am stuck on how to capture the request or requestBody so that I can assert against it.

Was looking for something similar to what I found on this SO post, but need access to the actual request and not the DOM. I am able to access the search params entered by the user (the 'text' param in my example) using currentUrl(), but the default params included in the request sent to the server, but not the url.

Is there a way to capture and assert against the request itself using ember-cli-mirage?

Something like

test('it appends default params to request'), function(assert) {
  let searchUrl = '/my/route/url';

  server.get(searchUrl, (db, request) => {
    assert.equal(request.requestBody, "text=abc&all=true");
  }
});