mardi 30 juin 2015

EmberJs Return Boolean from Function

I have the following code located in a route. It should create a discussion if it does not exist.

Although discussionAlreadyExist() is called, the code never executes inside the if statement even though the condition is matched.

actions: {
  createDiscussion: function(){
     var self = this;
     if(!self.discussionAlreadyExist()){
        //creatediscussion - why is this code is not being called ?
     }
  }
},

 discussionAlreadyExist: function(){
         return false;
  }




EmberJS conceptual inquiry - ember server

I know that emberJS is a front-end framework but why does it seem like a 'back-end' framework. Technically, why should there be an ember server? Isn't whatever back-end framework a dev uses like rails or django supposed to handle serving the html, js, etc, pages?




how do you deal with extra records that was created, but not used?

it's a common pattern to createRecord in the model hook when user enters the route.

Sometimes those records remain unused, and they pops up in certain conditions, i.e. in peekAll query, although that is unwanted. How do deal with them?




Ember Data does not allow duplicate entries in hasMany relationships

I have the following model:

//order/model.coffee
Order = DS.Model.extend {
  line_items: DS.hasMany 'products', {async: true}
}

At some point I want to add the some products to the order. I found that I can only add the product once, adding the same product again does not work:

//product/route.coffee
...
actions:
    addToCart: (product)->
      order = @modelFor 'order'
      console.log order.get('line_items.length') // prints 1
      order.get('line_items').pushObject product
      console.log order.get('line_items.length') // prints 1
      ...

How can I add a model more than once to a relationship ?




Why are the Ember component(s) for my notifications not being read/rendered?

I've been stumped on this issue all day and have exhausted all possible reasons I can think of. The problem is that my handlebar to display a notification if the user has one is not displaying.

As it is early on, I'm just testing it out by when I click 'Sign in' button, it sends a notification to the user (me in this case) just so I can see it working.

To put it simply...it doesn't work. I've attached an image showing the final result on a webpage, and it seems to comment out the handlebar line, and ignore it. And I've not a clue why.

I know the data is being read, as the other classes/componenets (the .js files, and other files) are able to return the data in the console. My 'main-header' components and 'main-footer' components renders/reads fine across all pages.

I'm also using a near-enough exact copy of another website's code that uses this. And it works perfectly. Originally I made some changes but earlier I copy-pasted everything I thought relevant, and it still didn't work.

Here is the HTML for the index.hbs (the homepage/page shown in the screenshot)

<div>

    {{main-header}}
    {{notification-list notifications=index.currentNotifications closeNotification='closeNotification'}}z

</div>

<!--Navbar - Home, About and Contact. Fixed position follows user down page-->
<header id="header" role="banner">
  <!-- Navigation -->
</header>

<!--Main Body-->
<div class="container">
  <br>
  <br><br><br><br><br><br><br>
  <button class="btn btn-primary btn-block btn-center" type="submit" {{action 'login'}}>
    Sign In
    &nbsp;
  </button>


  <!--Footer containing copyright, logos and social media-->
{{main-footer}}
</div>

The Homepage's .js file;

App.IndexRoute = Ember.Route.extend({

    model: function() {

    }
});

App.IndexView = Ember.View.extend({
    templateName: 'index'
});

App.IndexController = Ember.Controller.extend({

    needs: ['application'],
    currentNotifications: Ember.computed.alias("controllers.application.currentNotifications"),

    actions: {
        login: function() {
            console.log(this.currentNotifications);
            this.send( 'pushNotification', 'Message Sent', false );
        }
    }
});

The notification-list.hbs file (Btw, the original was made using '{{#each x in y}}' and I had to change that due to deprecation, but ultimately it should work the same I believe;

 <div class="container notify">
  <div class="row">
      {{#each notifications as notification}}
          {{#if notification.error}}
            <div class="alert alert-danger">
              <button type="button" class="close" data-dismiss="alert" aria-hidden="true"
                  {{action 'closeAlert' notification}}>
                ×
              </button>
              <span class="glyphicon glyphicon-hand-right"></span> <strong>{{notification.title}}</strong>
              <hr class="message-inner-separator">
                {{#each notification.message as message}}
                  <p>
                    <b>{{message.field}}</b>{{#if message.value}}: {{message.value}}{{/if}}
                  </p>
                {{/each}}
            </div>
          {{else}}
            <div class="alert alert-info">
              <button type="button" class="close" data-dismiss="alert" aria-hidden="true"
                  {{action 'closeAlert' notification}}>
                ×
              </button>
              <span class="glyphicon glyphicon-ok"></span> <strong>{{notification.title}}</strong>
              <hr class="message-inner-separator">
              <p>{{format-text notification.message}}</p>
            </div>
          {{/if}}
      {{/each}}
  </div>
</div>

And the associated notificationlist's .js file;

App.NotificationListComponent = Ember.Component.extend( {
    notifications: [],

    lastLength: 0,

    didInsertElement: function(){
        if(this.notifications != null){
            this.notifications.forEach(function(notification){
                Ember.run.later( this, function () {
                    if ( this.notifications.indexOf( notification ) >= 0 ) {
                        this.send( 'closeAlert', notification );
                    }
                }, 3000 );
            }, this)
        }
    },

    ////DO NOT REFERENCE IN HANDLEBARS
    timeout: function() {
        var lastLength = this.get( 'lastLength' );
        var notifications = this.get( 'notifications' );

        //check it was an added notification, not a destroyed one
        if ( notifications.length >= lastLength ) {
            var index = notifications.length - 1;

            if ( index >= 0 ) {
                var notification = notifications[ index ];
                Ember.run.later( this, function () {
                    if ( notifications.indexOf( notification ) >= 0 ) {
                        this.send( 'closeAlert', notification );
                    }
                }, 3000 );
            }
        }
        //update last length
        this.set('lastLength', notifications.length);
    }.observes('notifications.length'),

    actions: {
        closeAlert: function( notification ){
            this.sendAction('closeNotification', notification);
        }
    }

});

Finally the app.js file. I've left some parts off that I don't think is relevant (such as the Adapter and store etc) if its needed lemme know though, but its pretty much the standard/default ones;

App.ApplicationController = Ember.Controller.extend({

    currentNotifications: [],

    notification: Ember.Object.extend( {
        title: null,
        message: null,
        error: false
    } ),

    //Don't Call Directly, Use Route.Send to activate
    pushNotification: function( message, error ) {
        var currentNotifications = this.get( 'currentNotifications' );
        var notification = new this.notification;
        var test = error ? 'Failure' : 'Success';

        notification.setProperties( {
            title: test,
            message: message,
            error: error
        } );

        //Remove old message
        if(currentNotifications.length >= 4) {
            this.send('closeNotification', currentNotifications[0]);
        }

        currentNotifications.pushObject( notification );
    },

    closeNotification: function( notification ){
        var currentNotifications = this.get( 'currentNotifications' );
        var index = currentNotifications.indexOf(notification);
        //remove notification
        currentNotifications.removeAt(index);
    },

    updateCurrentPath: function() {
        App.set('currentPath', this.get('currentPath'));
    }.observes('currentPath')
});

The image showing the result of the above code. The highlighted line () is the line where the notification-list component is supposed to be




Sending action from component to route in ember.js

Here's the route:

import Ember from 'ember';

export default Ember.Route.extend({
    actions: {
        closeModal: function () {
            alert('asdf');
        }
    }
});

And the component js code:

import Ember from 'ember';

export default Ember.Component.extend({
    actions: {
        closeModal: function () {
            this.sendAction('closeModal');
        }
    }
});

What I'd like to do is to (as the code may suggest ;) ) send an action from component to route, so that the route could act upon it. However the code above doesn't work - component properly handles the action, but the sendAction call inside it's method doesn't do anything.




Refresh model with queryParam inside a function

I have a queryParams itemCount which is set to refreshModel: true. When I change this param, it triggers the model hook. The problem I have is I want to trigger the model hook in a function which depends on the newly retrieved content.

function :

loadUrlConvStatus: function(status){
        this.send('filterConversations', status);
        convCtrl = this.get('controllers.conversations');
        var convs = convCtrl.get('content').get('content')<--- Retrieved content;

        while(!this.get('convInLot')){

            var convs = convCtrl.get('content').get('content')<--- Content isnt changed right away

            for(j=convCtrl.get('itemCount'); j < convCtrl.get('itemCount') + 10; j++){
                if(convs[j].id == getCurrentConvId()){
                    this.set('convInLot', true);
                }
            }

            convCtrl.send('getMore');<----this function changes the param itemCount.
            **Model should then be refreshed. Model hook isn't triggered right away when I call it**
        }
    }

It is annoying because it only triggers the model hook only after it goes out of my function when I want to evaluate it right away (the variable convs retrieves the content).




Simple Ember component test with computed properties

I know this should be simple, I'm just not doing something right, and haven't found the example to mimic nor I guess do I fully understand what should go inside an Ember.run()

Here is my component code:

import Ember from 'ember';
export default Ember.Component.extend({
  isGreen: function() {
    if (!status) { return ''; }
    return status.toUpperCase() === 'G';
  }.property('status')
});

My component template:

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-green {{if isGreen 'active'}}">
    <input checked="checked" name="status" value="G" type="radio"/> Green
  </label>
  <label class="btn btn-yellow {{if isYellow 'active'}}">
      <input name="status" value="Y" type="radio"/> Yellow
  </label>
  <label class="btn btn-red {{if isRed 'active'}}">
      <input name="status" value="R" type="radio"/> Red
  </label>
</div>

And in my test:

test('status sets active class on the correct button', function(assert) {
  expect(3);
  var component = this.subject();

  //Green status
  Ember.run(function() {
    component.set('status', 'G');
  })
  equal(this.$().find('.btn-green.active').length, 1, 'When status is green, the green button has the active class');

I have three of these tests, one for each of three different statuses. If I have just one test, I don't need the to wrap component.set() in an Ember.run() in order for the test to pass. But if I have all three tests, I get this error:

You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in a run

But if I do put each of my component.set() calls in a run loop, then my tests fail due to the equal assertion expecting 1 and getting 0. I'm sure this is due to a lack of understanding on my part, but either the set() isn't running, or else the component gets re-rendered in the assertion and thus doesn't know that the status property was already set. I've been reading docs and googling for an hour, and haven't found a solution yet (and more beneficially, an explanation).




Ember Testing: Why use Assert.?

I see a lot of examples (including ember-cli generated tests) that use assert.function() but I can use the function as is, so am I doing something wrong, or do examples just show not-really-necessary qualifiers?

For example, either of these work in a new generated unit test:

assert.expect(1);

expect(1);

Why ever do the first one if the second one works?




Hooking ember-highcharts onto a rails API endpoint

I am trying to use Ember Highcharts to render some charts in EmberJS.

I have the component working with static data, by setting it in the controller as per the instructions:

chartData: [
  {
    name: 'Jane',
    data: [1, 0, 4]
  }, {
    name: 'John',
    data: [5, 7, 3]
  }
],

However, I'm not really sure how to hook the chartData property onto my rails API data. I am using Ember Data for the rest of my app but I thought that I should avoid it for the charts aspect as the chart data doesn't correspond to a particular model so it will get a bit messy. I thought that maybe something like this would work:

chartData: $.getJSON('api.enerlytics.local.dev:3000/v1/chart_data/4'),

but the chart is blank.

(NB: my rails API is returning the data in this format, maybe it's the extra root element that is causing issues?)

{
  "chart_data": [
    {
      "name": "First",
      "data": [
        [
          1214265600000,
          1
        ],
        [
          1214352000000,
          2
        ],
        [
          1214438400000,
          3
        ],
        [
          1214524800000,
          4
        ],
        [
          1214784000000,
          5
        ]
      ]
    },
    {
      "name": "Second",
      "data": [
        [
          1214265600000,
          5
        ],
        [
          1214352000000,
          4
        ],
        [
          1214438400000,
          3
        ],
        [
          1214524800000,
          2
        ],
        [
          1214784000000,
          1
        ]
      ]
    }
  ]
}




EmberJS large arrays and intensive functions block the UI

When a handlebars template that uses {{#each}} to iterate over a large array which is populated by a CPU intensive computed property, what are some possible solutions to prevent the UI from being frozen until EmberJS has finished all of its render queue tasks?

For example:

//template.hbs

{{#each obj in objects}} // objects is a computed prop. returning large array
   ...some html
{{/each}}

I have run the profiler and I think I have optimized the computed property as much as I can - EmberJS itself is where the browser is spending the vast majority of its time at this point.

Currently what is happening is that the UI freezes while EmberJS deals with all of the jobs in its work queues. When all of that is complete, the DOM populates. What I'm hoping is possible is to force the DOM to render the objects in that array say 100 or 1000 at a time, before ALL the jobs in the queues are finished, appending the views to the DOM every so often, so that the user at least sees something happening.

I suppose pagination might be one possible route to go, but that gets tricky because this particular page is a report that is doing calculations to get aggregate numbers on a decent chunk of data. Paginating wouldn't really help because I need the numbers to represent the entire dataset accurately.

I've also looked into this project: http://ift.tt/1bCkVfU, but implementing that would not be an insignificant amount of work.




Ember - get target url of transition

I am creating an error hook in my Ember.js app to redirect you to the auth service if you are not allowed to view certain content (in other words, if the server returns a 401).

It looks like this:

Ember.Route = Ember.Route.extend({
  error: function(error, transition){
    if (error.status === 401) {
      window.location.replace("http://ift.tt/1RPWWyz");
    }
  }

Our auth api works as follows: If you send it a parameter called target (which is a url), it will redirect you back to that target url after you've logged in.

So I want to somehow get the URL of the route the Ember app was trying to transition to.

Then my code will end up something like this

Ember.Route = Ember.Route.extend({
  error: function(error, transition){
    if (error.status === 401) {
      var target = // Your answer here
      window.location.replace("http://ift.tt/1RPWWyD" + encodeURIComponent(target));
    }
  }




rails-api ember js polymorphic association

On my Rails Api, I have 3 models User, Property, and Address. Each Users and Properties can have one Address and Address is set as a polymorphic association as following:

address.rb

class Address < ActiveRecord::Base
  belongs_to :locatable, polymorphic: true
end

user.rb

class User < ActiveRecord::Base
  has_one :address, as: :locatable, dependent: :destroy
end

property.rb

class Property < ActiveRecord::Base
  has_one :address, as: :locatable, dependent: :destroy
end

In my addresses I have following fiels: locatable_type and locatable_id as well as the necessary fields for the address body.

My specs are passing on the rails side but when I am having hard to implementing this association in Ember. I use the ActiveModelSerializer gem on the rails side and the ActiveModelAdapter on the ember side.

So, I was wondering whether someone could point me to the direction to follow in order to getting these associations set in Ember.

Thanks,




Name conflict when sideloading models

Consider the following code:

{
   "post":{
      "id":1,
      "title":"Killing Koopas",
      "author":"Super Mario",
      "categories":[
         12,
         41
      ],
      "translations":{
         "en":{
            "title":"Something",
            "content":"A long text"
         },
         "es":{
            "title":"Algo",
            "content":"un texto largo"
         }
      }
   },
   "categories":[
      {
         "id":12,
         "translations":{
            "en":{
               "title":"News",
               "description":"a description"
            },
            "es":{
               "title":"Noticias",
               "description":"una descripción"
            }
         }
      },
      {
         "id":41,
         "translations":{
            "en":{
               "title":"Sport",
               "description":"another description"
            },
            "es":{
               "title":"Sport",
               "description":"otra descripción"
            }
         }
      }
   ]
}

As you can see both "post" and "categories" models have a "translations" field with different sub-fields. This is a simplified version of my real model. How would you map a JSON structure like this one to Ember Data?




In an Ember Component where should you put reusable code that isn't an action?

I have a standard component defined something like:

export default Ember.Component.extend({
  hideIfEmptyChange: function() {

    var thingOfInterest = ...;
    var otherThingOfInterest = ...;

    ...
    // Perform some logic
    ...

    // Perform some logic using thingOfInterest
    // Perform exactly the same logic using otherThingOfInterest
  }.observes('hideIfEmpty.@each')
});

I want to move the logic for the last two pieces into their own function to prevent writing out the same code twice just for two different variables.

I could write an action on my component and use this.send('myAction',...) - but would it be best practice to have this as an action if it isn't going to be used (or even usable) from the component's template? If you shouldn't do it this way then how should you?

My other thought was mixin's - but the code here will be completely specific to the component, so again this doesn't feel 100% right.




Ember: Prevent transition based on response

In Ember.js, how do you conditionally prevent transition based on response?

For example, if the server returns a 403 (in the model hook), then display an alert and do not transition.

It's such a simple and common thing to do, yet I cannot find any documentation or guides to do so.




Ember distinguish record which is requested from server with params and without params

I'm trying to get two records from the server without knowing the ID's. The first record is requested without params and the second record with params.

It looks something like this:

model: function(){

  return Ember.RSVP.hash({
    cars: this.store.find('cars').then(function(car){
      return car.get('firstObject');
    }),

    carsWithRange: this.store.find('cars', {date_from: momentLast30Days}).then(function(car){
      return car.get('firstObject');
    })
  });
}

At the moment 'cars' and 'carsWithRange' sometimes returns the same record. I think this is happening because I use car.get('firstObject') from the cars models. Somehow I need to know that 'carsWithRange' is requested with the param 'date_from'.

Does anyone know how to fix this?

FYI I use Ember 1.12.1 with Ember Data 1.0.0-beta.15




lundi 29 juin 2015

Ember: bind-attr title attribute does not decode properly

My model returns encoded values from the server. The model contains "enc_res_name" which is HTMLEncoded to display inside an element and "encattr_res_name" which is Attribute Encoded to set as attributes to an element.

The issue I am facing is the HTMLEncoded value displays properly within the element. But the title attribute which is set using "bind-attr" does not rendered properly. The Encoded value is displayed as such in the title.

Template:

<ul>
    {{#each item in model}}
        <li>
            <a {{bind-attr title=item.encattr_res_name}}>     
                {{{item.enc_res_name}}}
            </a>
        </li>
    {{/each}}
</ul>

Route:

App.IndexRoute = Ember.Route.extend({
    model: function() {
        return [{'enc_res_name':'&lt;div onmouseover&#x3d;&quot;alert&#x28;document.cookie&#x29;&#x3b;&quot;&gt;haii&lt;&#x2f;div&gt;','encattr_res_name':'&lt;div&#x20;onmouseover&#x3d;&quot;alert&#x28;document.cookie&#x29;&#x3b;&quot;&gt;haii&lt;&#x2f;div&gt;'}];
    } 
});

One solution to set the encoded values to title is use triple curly braces and unbound. But there is an option to rename the value where I need to update the title attribute also.

So I am not sure how to set the title attribute to render the encoded values as human readable.

JSBin Link




Rails 4: Request view only access to users records (Self-Referential)

My goal is to give users a way to send requests to share there records with a user with director role and the inverse of director user requesting. So after some investigation, I realized the setup was very similar to how social media platforms send friend requests. However the requests would be one sided for viewing records.

User A wants to share his 'records' with User B who has the managerial type role.

I have concluded this has to do with making a table called 'Requests' at which has states of [pending, accepted]. Maybe another state for sent?

So far I came up with

 rails g model request user:reference status:string

Model Files

 class Request < ActiveRecord::Base
   belongs_to :user
   belongs_to :student, class_name: 'User', foreign_key: 'user_id'
 end


 class User < ActiveRecord::Base
   ...

   has_many :students
   has_many :requests
   has_many :accepted_requests, :class_name => "Request", # conditions doesn't work on rails 4
   has_many :pending_requests, :class_name => "Request" # conditions doesn't work on rails 4

   ...
 end

Ember CLI Model (User)

export default DS.Model.extend({
  requests: DS.hasMany('request')
  students: DS.hasMany('student', {inverse: true});
});

A couple good resources I found but wasn't sure how to implement as one-sided.

Friendship has_many through model with multiple status'

http://ift.tt/PjCZii

Anybody guide me to the next step or missing parts?




After setting manually, computed property do not observe changes anymore

here is jsbin http://ift.tt/1U2pOaK with input where it is possible to enter id of the item and its text will be displayed nearby. But there are two items with same "id" property and thus to display correct text they can be selected from the list on the bottom.

With "manual selection" itemId is changed only once - very first time , afterwards it's not set and subsequently "itemText" CP which observes itemId is not triggered.

The weird thing is that this effect is caused by setting value for "itemText" CP, and doesn't occur when this.setProperties({'itemId': item.id, 'itemText': item.text}); is replaced with this.setProperties('itemId', item.id); Why's that?




Emberjs - Uncaught TypeError:

js and handlebars code: http://ift.tt/1LEQbRv

On a forum website built with ruby on rails, polls are created using emberjs and handlebars. I am totally new to this so I need help. The poll updates everything apart from min/max params after clicking edit and save. So I inspected the elements and on the console I got after editing and clicking update:

Uncaught TypeError: Cannot read property 'insertBefore' of null

html i'm inspecting:

<div class="cooked">
        <div><div id="ember3782" class="ember-view poll" data-poll-type="multiple" data-poll-name="poll" data-poll-status="open"><div>
<div class="poll-container" style="height: 235px;">
    <ul>
        <li id="ember3801" class="ember-view" data-poll-option-id="5b8ee5ba2a43e258f93dbef9264bf1ad" data-poll-selected="false">Option A</li>
        <li id="ember3803" class="ember-view" data-poll-option-id="6872645f5d8ef2311883617a3a7d381b" data-poll-selected="false">Option B</li>
        <li id="ember3805" class="ember-view" data-poll-option-id="f87018a545c87172dc094ab5f6266f45" data-poll-selected="false">Option C</li>
        <li id="ember3807" class="ember-view" data-poll-option-id="953d2e70ca3da6b3e0467bd902209b35" data-poll-selected="false">Option D</li>
        <li id="ember3809" class="ember-view" data-poll-option-id="d74ff774286f3a4334ace31c8c08d28e" data-poll-selected="false">Option E</li>
    </ul>
</div>
<div class="poll-info">
  <p>
    <span class="info-number">0</span>
    <span class="info-text">voters</span>
  </p>
      <p>You may choose up to <strong>5</strong> options.</p>
      </div>
     </div>
<div class="poll-buttons">
  <button id="ember3814" class="ember-view cast-votes btn" disabled="" title="Cast your votes">Vote now!</button>

  <button id="ember3816" class="ember-view toggle-results btn" disabled="" title="Display the poll results"><i class="fa fa-eye"></i> Show results</button>

So something going on and its got do do with this error and wont update. A problem with ngrepeat with others after doing some research? I'm totally new with ember and rails, but i'll understand quick . I need help please.




Ember application container change 1.12

In 1.11 i could use this.container to access the container element inside the helper function. However in 1.12 this relates to the window object. and not the ember application in which i believe this container thing sits. How could may i access the container now?




ember js creating multiple divs in template through model but user interaction in one div is duplicated across all divs

I realize that this may be a rather vague and non specific question but here is my problem- I am creating multiple divs in my template populated via my model through the {{#each}} helper. In those divs I have inputs and checkboxes but interactions in one div gets duplicated in the other divs. I am at a loss of words and unable to find a better way to explain it.

I am an ember newbie and don't understand Views in Ember yet. Some general pointers might help , Should I look into views to solve this?




Best practices for testing components that accept collection of models in Ember.js

I have a component, that accepts a collection of models (ember-data). I also have http-mock setup for mock testing.

Now the question is when I'm testing this component, how should I pass it the collection of models that it needs?




Ember.js: there is no route named 'new-table'

Here are my routes definition:

Router.map(function() {
    this.resource('servers', { path: '/' }, function() {
      this.resource('server', { path: '/servers/:serverid'}, function () {
          this.resource('databases', { path: '/databases' }, function () {
              this.resource('database', { path: '/:databaseid'}, function () {
                  this.resource('catalogues', { path: '/catalogues' });
                  this.resource('eventtriggers', { path: '/eventtriggers' });
                  this.resource('extensions', { path: '/extensions' });
                  this.resource('schemas', { path: '/schemas' }, function () {
                      this.resource('schema', { path: '/:schemaid' }, function () {
                          this.resource('tables', { path: '/tables' }, function () {
                              this.route('new-table', function () {});

                              this.resource('table', { path: '/:tableid' });
                          });
                      });
                  });
                  this.resource('replication', { path: '/replication' });
              });
          });
      });
    });
});

And the code used to generate link to new-table route goes as follows:

{{#link-to 'new-table' schema.database.server.id schema.database.id schema.id}}

And this gives me the error mentioned in this question's topic. However when I replace this.route call to this.resource everything works fine. So what am I doing wrong here? I'm using ember 1.13.2.




Incorporating 3rd-party theme to ember-cli project / Brocfile / outputPaths / multiple outputs

I want to use Inspinia ( http://ift.tt/1meHqjj ) in my ember project built using ember-cli.

This inspinia comes with set of files (css, jss, fonts, etc) in particular structure / layout. I need to reflect that structure in the outcome of ember-cli build-process.

The way I (try to) integrate is as follows:

  1. I copied the entire folder inside Inspinia Seed-Project into my ember-cli's vendor folder, under subfolder that I name "inspinia". There we have subfolders: css, font-awesome, fonts, img, js.

enter image description here

  1. Then I added these lines to my Brocfile (still, not including any Inspinia stuffs). Just the bootstrap:

    app.import('bower_components/bootstrap/dist/css/bootstrap.css'); app.import('bower_components/bootstrap/dist/css/bootstrap-theme.css');

enter image description here

All, fine. Bootstrap stuffs go to vendor.css under assets/. The default behavior.

  1. Then I added these lines (now from Inspinia) to the Brocfile.

    app.import('vendor/inspinia/css/animate.css'); app.import('vendor/inspinia/css/style.css');

enter image description here

All is "fine", in the sense that the project compiles, animate.css and style.css appended to vendor.css (still the default behavior).

But I want to make animate.css and style.css goes to assets/inspinia/css/animate.css and assets/inspinia/css/style.css, respectively. So...

  1. I tried this:

    var app = new EmberApp({ outputPaths: { app: { html: 'index.html', css: { 'app': '/assets/dash-imss.css' }, js: '/assets/dash-imss.js' },

    vendor: {
      css: {
        'inspinia/css/animate': 'assets/inspinia/css/animate.css',
        'inspinia/css/style': 'assets/inspinia/css/style.css'
      }
    }
    
    

    } });

enter image description here

But now the compilation fails with an error:

undefined is not a function
TypeError: undefined is not a function
  at module.exports (/Users/raka/Documents/MyEmberCLIPlayground/dash-imss/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/index.js:24:38)

I already added come console.logs to broccoli-sourcemap-concat/index.js, so I can see the difference between successful compile (step 2 and 3) and this failed compile; In the successful compile, outputFile is a string. In the failed compile (step 4), the outputFile is a json object. It doesn't have slice function.

I tried some other arrangements in my Brocfile (in that outputPaths specification). None of them works. And I couldn't find any article / discussion on the web on this topic.

Can someone help me solve this?

Thanks in advance, Raka




My ember-simple-auth authenticator cannot call super. Why is that?

I'm trying to implement an authenticator such that it will let me send a client_id with OAuth. In app/authenticators/oauth-custom.js:

import Authenticator from 'simple-auth-oauth2/authenticators/oauth2';

export default Authenticator.extend({
  makeRequest: (url,  data) => {
    data.client_id = EmberENV.clientId;
    return this._super(url, data);
  }
});

This however generate an error when I attempt to sign in:

TypeError: Cannot read property '_super' of undefined

The source map seem to suggest that _this is set to be undefined.

define('frontend/authenticators/oauth-custom', ['exports', 'simple-auth-oauth2/authenticators/oauth2'], function (exports, Authenticator) {

  'use strict';

  var _this = undefined;

  exports['default'] = Authenticator['default'].extend({
    makeRequest: function makeRequest(url, data) {
      data.client_id = EmberENV.clientId;
      return _this._super(url, data);
    }
  });
});

I'm using the current latest ember-cli 0.2.7, ember 1.13.2, ember-simple-auth 0.8.0. What's the issue?




An error occurred while installing pg (0.18.2), and Bundler cannot continue

Following Tony Coconate's Rails + Ember.js (with the Ember CLI) tutorial, we are trying to create a new Rails API.

When we run rails new api -T -d postgresql, we get the following error message:

An error occurred while installing pg (0.18.2), and Bundler cannot continue.
Make sure that `gem install pg -v '0.18.2'` succeeds before bundling.

This is what the Gemfile file looks like:

source "https://rubygems.org"

gem "rails", "4.2.1"

gem "activeadmin", github: "gregbell/active_admin" # Until it"s 1.0.0
gem "coffee-rails", "~> 4.0.0"
gem "devise"
gem "grape"
gem "grape-active_model_serializers"
gem "grape-swagger-rails"
gem "jquery-rails"
gem "pg"
gem "rack-cors", require: "rack/cors"
gem "sass-rails", "~> 4.0.3"
gem "uglifier", ">= 1.3.0"

group :development do
  gem "better_errors"
  gem "meta_request"
  gem "quiet_assets"
  gem "spring"
end

group :development, :test do
  gem "capybara"
  gem "capybara-screenshot"
  gem "database_cleaner"
  gem "factory_girl_rails"
  gem "faker"
  gem "poltergeist"
  gem "pry-nav"
  gem "pry-rails"
  gem "pry-stack_explorer"
  gem "pry-theme"
  gem "rspec-rails"
  gem "rubocop"
  gem "shoulda-matchers"
  gem "spring-commands-rspec"
end

When we run bundle install, we get the following error message:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /Users/user_name/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20150629-73521-9m0ocx.rb extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/user_name/.rvm/rubies/ruby-2.2.1/bin/$(RUBY_BASE_NAME)
    --with-pg
    --without-pg
    --enable-windows-cross
    --disable-windows-cross
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib

extconf failed, exit code 1

Gem files will remain installed in /Users/user_name/.rvm/gems/ruby-2.2.1/gems/pg-0.18.2 for inspection.
Results logged to /Users/user_name/.rvm/gems/ruby-2.2.1/extensions/x86_64-darwin-14/2.2.0-static/pg-0.18.2/gem_make.out
An error occurred while installing pg (0.18.2), and Bundler cannot continue.
Make sure that `gem install pg -v '0.18.2'` succeeds before bundling.

When we run gem install pg -v '0.18.2', we also get an error:

Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

    /Users/user_name/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20150629-73553-uaymt5.rb extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/user_name/.rvm/rubies/ruby-2.2.1/bin/$(RUBY_BASE_NAME)
    --with-pg
    --without-pg
    --enable-windows-cross
    --disable-windows-cross
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib

extconf failed, exit code 1

Gem files will remain installed in /Users/user_name/.rvm/gems/ruby-2.2.1/gems/pg-0.18.2 for inspection.
Results logged to /Users/user_name/.rvm/gems/ruby-2.2.1/extensions/x86_64-darwin-14/2.2.0-static/pg-0.18.2/gem_make.out

Any idea of what is wrong, and most importantly, how we can fix it?




Ember unable to transition to route

Suppose I was at abc.com/a?id=1 (Transition 1 T1), I want transitionToRoute to make a another full transition to abc.com/a?id=2 (Transition 2 T2).

T1: resolves correctly - a's model correctly in a's router and var t1 = this.transitionToRoute('a',{queryParams:{id:1}}) returns a healty object.

The promise object, below, of the transition dump is: "Router: Settle transition promise when transition is finalized"

Transition {state: TransitionState, intent: C, router: Router, data: Object, resolvedModels: Object…}
 _visibleQueryParams: Objectdata: 
ObjecthandlerInfos: Array[2]
intent: C
isActive: false
params: ObjectpivotHandler: Class
promise: Promise
queryParams: Objectresolve
Index: 1
resolvedModels: Object
router: Router
sequence: 2
state: TransitionState
targetName: "index"

Ok.

Now we are in the route of T1 , so in controller a, we send an action to bubble up to the index main application controller in order to re-transition to a with new set of parameters (T2).

T2: Resolves incorrectly with var t2 = this.transitionToRoute('a',{queryParam:{id:2}}. All parameters are missing objects, the intent is undefined and the promise reads "Router: Transition complete"

Transition {state: TransitionState, intent: undefined, router: Router, data: Object, resolvedModels: Object…}
_visibleQueryParams: Object
data: Object
intent: undefined
params: Object__proto__: Object
promise: Promise_id: 847_label: "Router: Transition complete"_onerror: null_result: TransitionState_state: 1
_subscribers: Array[0]
__proto__: Promisequery
Params: Object
__proto__: Object
__defineGetter__: __defineGetter__() { [native code] }__defineSetter__: __defineSetter__() { [native code] }__lookupGetter__: __lookupGetter__() { [native code] }__lookupSetter__: __lookupSetter__() { [native code] }constructor: Object() { [native code] }hasOwnProperty: hasOwnProperty() { [native code] }isPrototypeOf: isPrototypeOf() { [native code] }propertyIsEnumerable: propertyIsEnumerable() { [native code] }toLocaleString: toLocaleString() { [native code] }toString: toString() { [native code] }valueOf: valueOf() { [native code] }get __proto__: __proto__() { [native code] }set __proto__: __proto__() { [native code] }queryParamsOnly: trueresolvedModels: Object__proto__: Objectrouter: Routerstate: TransitionState__proto__: Object

I totaly don't understand why a second full transition to the same route, fails with changed parameters. I've tried to work around this, but as long as I'm calling the same route, transition objects are the same.

How would you update your model with a new parameter that you set?




Render select with optgroup from a given product list

I can create a select field of all products with this code:

{{view "select" prompt="All Products"
                content=model.products
                optionLabelPath="content.name"
                optionValuePath="content.name"
                value=selectedProduct
                class="form-control"}}

But I'd like to render the products in optgroups to have a nice UX: Screenshot of the form

The data I fetch from the server looks like this:

{
  products: [
    {
      id: 1,
      name: "Vegetables"
    },
    {
      id: 2,
      name: "Tomato",
      parent: 1
    },
    {
      id: 3,
      name: "Potato",
      parent: 1
    },
    {
      id: 4,
      name: "Fruits"
    },
    {
      id: 5,
      name: "Apple",
      parent: 4
    }
  ]
}

How can I render the select field in a way that it includes the products in optgroups depending on the parent attribute?




Rails API / Ember-cli web app: what is the conventional workflow?

In the process of building a SPA, we opted for a combination of Rails API and Ember-cli.

From what we understand, the architecture of the app will be the following:

  • Rails API will run the back-end of the app, as an API
  • Ember-cli will run the front-end of the app, as a front-end MV* framework
  • Data will be served by Rails API to Ember-cli with JSON

What does not seem really clear though, is what should be the development workflow?

In other words, should we:

  1. Build the back-end (rails models, etc), then build the front-end and finally connect both?
  2. Build everything at the same time, but one feature at a time?
  3. Go with another option?



new Date(epoch) returning invalid date inside Ember component

I have a date-filter component that I am using in my Ember application that only works on initial render, not on a page reload, or even if I save a file (which triggers the application to live update).

In the main template of my application, I render the date-filter like this passing it a unix timestamp

{{date-filter unixepoch=item.date}}

Then, in components/date-filter.js, I use a computed property called timeConverter to change the unix epoch into a time string formatted according to user's language of choice, and then in my templates/components/date-filter.hbs file I do {{timeConverter}} to display the results

timeConverter: function(){
    //step 1: get the epoch I passed in to the component
    var epoch = this.get('unixepoch');
    //step 2: create a human readable date string such as `Jun 29, 2015, 12:36PM`
    var datestring = new Date(epoch)

    //do language formatting --code omitted as the problem is with step2

}

It is step 2 that fails (returning invalid date) if I refresh the page or even save the file. It always returns the proper date string the first time this component is called. Even if I do new Date(epoch) in the parent component, and try to pass the result in to this component (to do foreign language formatting), I'm having the same problem.

Question: how can I figure out what's happening inside new Date(epoch), or whether it's an issue related to the component?




ember route event didTransition timing

I want to open a modal in a route after transitioning to it. My guess is to use the "didTransition" event. In the called method (a util) I refer to an Ember.View object.

My route actions:

actions: {
  openModal: modal.open,
  closeModal: modal.close,
  toggleModal: modal.toggle,

  didTransition: function() {
    this.send('openModal', 'choose');
  }
}

The problem is using:

didTransition: function() {
    this.send('openModal', 'choose');
}

doesn't work (because the view object is undefined, see further down in utils), but using:

didTransition: function() {
    setTimeout(function() {
        self.send('openModal', 'choose');
    }, 0);
}

does work.

Why does it not work with the standard call? I guess it's a problem with synchronicity.

The utils looks as following:

import Ember from 'ember';

export default {
  open: function(id) {
    console.log('utils open');
    var modal = Ember.View.views[id];

    // test output for debugging
    console.log(modal);

    modal.send('open');
  },
  close: function(id) {
    var modal = Ember.View.views[id];
    modal.send('close');
  },
  toggle: function(id) {
    var modal = Ember.View.views[id];
    modal.send('toggle');
  }
};

Am I missing something or is there a better method for doing this? I am using ember.js 1.12.0.




Ember.js working with async relationship inside the controller

I have 2 models:

App.Center = DS.Model.extend({
    name: DS.attr('string'),
    code: DS.attr('string'),
    studies: DS.hasMany('study', {async: true})
});

App.Study = DS.Model.extend({
    center: DS.belongsTo('center'),
    //other data
});

In theory, Ember will wait for the studies promise to be resolved and then render the template to display them. For the common scenarios this is very good.

I must implement some filtering and other operations on the Center's studies inside the CenterStudiesController.

The problem is that center.get('studies') is an empty array inside the controller. How could I wait for them to be loaded?

I don't want to modify the server code in order to sideload the studies.

Is there a way to do this?




Ember - Path or pattern "vendor/ic-ajax/dist/named-amd/main.js" did not match any files

I have an ember app with ember-cli running perfectly on my MacBook Pro. Now I've installed ember on another MacBook Pro, downloaded the same git repo and ran ember s, which gives me this error trace:

compiler.js:17942:7)
    Walker.visit (/Users/Jensherf/shopstar-u/bower_components/ember/ember-template-compiler.js:17910:12)
    visitors.Program (/Users/Jensherf/shopstar-u/bower_components/ember/ember-template-compiler.js:17919:16)
Path or pattern "vendor/ic-ajax/dist/named-amd/main.js" did not match any files
Error: Path or pattern "vendor/ic-ajax/dist/named-amd/main.js" did not match any files
    at Object.multiGlob (/Users/Jensherf/shopstar-u/node_modules/broccoli-kitchen-sink-helpers/index.js:203:13)
    at Class.module.exports.CachingWriter.extend.addFiles (/Users/Jensherf/shopstar-u/node_modules/broccoli-sourcemap-concat/concat-with-maps.js:74:13)
    at Class.module.exports.CachingWriter.extend.updateCache (/Users/Jensherf/shopstar-u/node_modules/broccoli-sourcemap-concat/concat-with-maps.js:52:12)
    at /Users/Jensherf/shopstar-u/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/index.js:92:34
    at lib$rsvp$$internal$$tryCatch (/Users/Jensherf/shopstar-u/node_modules/rsvp/dist/rsvp.js:489:16)
    at lib$rsvp$$internal$$invokeCallback (/Users/Jensherf/shopstar-u/node_modules/rsvp/dist/rsvp.js:501:17)
    at lib$rsvp$$internal$$publish (/Users/Jensherf/shopstar-u/node_modules/rsvp/dist/rsvp.js:472:11)
    at Object.lib$rsvp$asap$$flush [as _onImmediate] (/Users/Jensherf/shopstar-u/node_modules/rsvp/dist/rsvp.js:1290:9)
    at processImmediate [as _immediateCallback] (timers.js:345:15)

In this output, the sentence "Path or pattern "vendor/ic-ajax/dist/named-amd/main.js" did not match any files" is in red.

I cannot figure out how to fix this. Why would the app be looking in the vendor/ folder for this library? Shouldn't it be in bower components or node modules? Does anyone have an idea what should be in this file?

Here is my .gitignore file just for completeness:

# See http://ift.tt/Vpfznc for more about ignoring files.

# compiled output
/dist
/tmp

# dependencies
/node_modules
/bower_components

# misc
/.sass-cache
/connect.lock
/coverage/*
/libpeerconnection.log
npm-debug.log
testem.log




Ember JS unable to access sliced value to computed Array in template

I am facing a very weird problem. I created an array in my conroller as

    'brandsSelectedForTrade':Ember.ArrayController.create(),

    //populating array 
    actions:{
  'addBrandToTrade':function(brand){
       this.get('brandsSelectedForTrade').addObject(brand);
        console.log(this.get('brandsSelectedForTrade'));
    var test=this.get('brandsSelectedForTrade').slice(0,3);
      //  console.log(this.get('brandsSelectedForTrade').slice(0,3));
      test.forEach(function(val){
         console.log(val.get('Brandname'));
      });
},

//Returning array to view
  tradeDropDownSelectedBrands:function(){
    // console.log(this.get('brandSelectedForTrade'));
     var retVal= this.get('brandsSelectedForTrade').slice(0,3);
   // var returnContent={'brandsSelectedForTrade':retVal};
    return retVal;


  }.property('brandsSelectedForTrade','brandlistingStartVal','brandlistingEndVal')

In my template I am accessing the array as

{{#each brand in tradeDropDownSelectedBrands}}
    //Do something
{{/each}}

If I am passing the unsliced array I am able to access the properties but somehow if I try to access the sliced array it is null in the template. Any Idea what I am doing wrong? If I am correct Ember.ArrayController.create() has the slice() method. And doing a console.log of the sliced array does show an array of classes




Ember 1.13 - DS.attr deprecation

I've upgraded to Ember v1.13.0, and now I have a couple of deprecation warnings (as expected) but I can't find any clue as to how to get rid of them. Ember has provided some links to the guides but they are useless and disappointing.

The most common deprecation I have is for the DS.attr('type') method on Ember.Model.

How does the new syntax work? Please provide an example by converting this model into the new format

import DS from 'ember-data';

var Order = DS.Model.extend({
  price: DS.attr('number'),
  date: DS.attr('string'),
  shopName: DS.attr('string'),
  shippingStatus: DS.attr('string'),
  destination: DS.attr('string'),
  dueFor: DS.attr('string')
});

export default Order;




Double definition required in belongsTo and hasMany with FIXTURES?

I'm testing out a very simple model relationship. I'm using the Fixture adapter before I switch to a true back-end. Somewhat following from here and here, I've found I need to define both sides of the relationship in each Fixture.

Is that a restriction of the Fixture adapter or will the backend/database also have to store both sides (which is non-standard for something like SQL)?

Models:

// app/models/comment.js
...
export default DS.Model.extend({
  text: DS.attr('string'),
  author: DS.attr('string'),
  //post: DS.belongsTo('post', {async: true})  // async only needed on one side - true??
  post: DS.belongsTo('post')
}).reopenClass({
FIXTURES: [
    {
      id: 1,
      text: 'Text of the comment goes right in here',
      author: 'Fred',
      post: 1
    },
    {
      id: 2,
      text: 'TWO 2222 comment two here',
      author: 'Barney',
      post: 1
    },
    {
      id: 3,
      text: 'third comment here',
      author: 'Wilma',
      post: 2
    },
...

// app/models/post.js
...
export default DS.Model.extend({
  text: DS.attr('string'),
  comments: DS.hasMany('comment', {async: true})
}).reopenClass({
    FIXTURES: [
    {
      id: 1,
      text: 'Post ONE - Lorem ipsum dolor sit amet, consectetur risus.',
      comments: [1,2]  // Why is this required??
    },
    {
      id: 2,
      text: 'Post TWO - consectetur adipiscing elit. Sed gravida faucibus risus.',
      comments: [3,4]  // Why is this required?
    },
...

My ember info:

  • Ember Inspector 1.8.2
  • Ember 1.12.0
  • Ember Data 1.0.0-beta.18
  • jQuery 1.11.3



dimanche 28 juin 2015

Ember JS how to set property accessible in all templates

This is a pretty noobie question but I searched for this over the internet in vain for many days now.

I am building an Application which has an Ember front end server connecting to a Node JS back end. For development and testing both Node and Ember are running on my local machine at localhost:3000 and localhost:4200 respectively. However some resources like images etc. are getting saved on the Node server and to fetch those resources I am having to hardcode the server ip in my template. For instance <img src="http://localhost:3000/"{{brand.imgLocation}}/>

This is a nightmare because whenever I need to update to production server I am having to change it to Node Server IP in every place across all templates which is inconsistent. Is there a place where I can store it as a property accessible to all templates ,I tried saving it as a property in Index Controller but it is not accessible in other templates except for Index template.




Emberjs loadInitializer error

Not sure how to correct this error. I'm following along with this screencast https://www.youtube.com/watch?v=vLXGKNA4P_g and it appears that the update to Ember breaks functionality.

DEPRECATION: `lookup` was called on a Registry. The `initializer` API 
no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container. 
See http://ift.tt/1NsjWCm
instances-in-initializers for more details.

I'm new to Ember and have found the http://ift.tt/1TZoc1m thread on github but I'm not quite sure how to fix this. This is my app.js file

import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

var App;

Ember.MODEL_FACTORY_INJECTIONS = true;

App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;

Can someone explain how to make this compliant with the error? The documentation suggests this:

http://ift.tt/1B0z5ED

But being new to Ember, I'm not sure what this means or how to implement it.




How to change url instantly without waiting for model to load?

Is there any way to change page url instantly when clicking on a link without waiting for the model to load?

I'm using ember-data.




Ember add title attribute to table header

I have a table header and need to add title attribute in ember

      {{#each orderedOptionPools as |optionPool|}}
        <th title="?">{{optionPool.planName}}</th>
      {{/each}}

I've tried adding {{optionPool.planName}} but can't get it to work.. any ideas?




Binding static and dynamic classes with HTMLBars

I'm trying to bind a static class 'form-control' and a dynamic property value 'color' to the class attribute of an input helper, however, the syntax I'm using just outputs this to the rendered DOM element

class="form-control {{color}}" 

without actually binding the value of 'color' to the class attribute. I know that this is the way to bind static and dynamic classes in normal DOM elements with HTMLBars, but is there a different syntax for elements that use curly-braces?

The syntax I'm using:

{{input class="form-control {{color}}" value=property.value type="text"}}




How to call an action on a route using closure actions?

I've got openModal action defined on application route. I'm trying to call this action from within a component.

If I use syntax for action bubbling:

{{my-component openModal="openModal"}}

then everything works as expected and I can trigger this action using this.sendAction("openModal").

However, I'm not sure how to get the same result using the new closure syntax:

{{my-component openModal=(action "openModal")}}

In this case, Ember complains that there's no action openModal defined on the controller. Do I have to define this action on every controller that uses my-component? Is there a way to somehow use target option to tell Ember that this action is defined on a route? Is it ok to mix bubbling and closure syntax in a single component?

I'm using Ember 2.0 beta 1.




How do I add relationships to an Object in the EmberData (v. 1.13.4) store?

I have a basket object and many fruit objects. When I want to add a new fruit into a basket how do I add the new fruit into the basket with ember data?

store.push('basket', {
                        id: 1,
                        fruits: [3]
                    });

This overwrites the existing fruits array in the store, which i don't want.

Is there a way to merge the content of the fruits array? How is this done in a clean and simple way?




What happens when you bind 'this' on an Ember function?

I'm trying to better understand this Firebase authenticator for Ember SimpleAuth:

import Ember from 'ember';


export default Ember.Controller.extend({


actions: {
    login: function() {
        this.get('session').authenticate('authenticator:firebase', {
            'email': this.get('email'),
            'password': this.get('password')
        }).then(function() {
            this.transitionToRoute('index');
        }.bind(this));
    },
    logout: function() {
        this.get('session').invalidate().then(function() {
            this.transitionToRoute('login');
        }.bind(this));
    }
}

});

Would someone please explain what ".bind(this)" is doing and how exactly bind is working in this particular instance?




Ember Data hasMany relationship empty result

I'm using ember-cli 0.2.7 and I'm not sure why but it seems that I can't retrieve the tags for my newsletter model.

newsletter.js

import DS from 'ember-data';

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

tag.js

import DS from 'ember-data';

export default DS.Model.extend({
  newsletter: DS.belongsTo('newsletter', {async: true}),
  name: DS.attr('string')
});

API response (rails backend using ActiveModelSerializer):

{
  "newsletters": [
    {
      "id": 1,
      "title": "Panel Weekly",
      "tag_ids": [
        1
      ]
    },
    {...}
  ],
  "tags": [
    {
      "id": 1,
      "name": "arts"
    },
    {...}
}

I don't know how to retrieve the list of tags for a newsletter. I tried this using the ember inspector and the console ($E containing the first newsletter):

>$E.get('tags.length')
0
>$E.get('tags')
Class {canonicalState: Array[0], store: Class, relationship: ember$data$lib$system$relationships$state$has$many$$ManyRelationship, record: Class, currentState: Array[0]…}
>$E.get('title')
"Panel Weekly"




Kayak like URL instead of query parameters

I have a small app which reads parameters from the URL.

Example: http://localhost:4200/flights?from=FRA&to=JFK

I'd like to offer the user a Kayak like URL like: http://localhost:4200/flights/FRA-JFK

Can this be done with Ember without doing the mapping in the webserver?

app/controllers/flights.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['from','to'],
  from: null,
  to: null,

  filteredFromFlights: function() {
    var from = this.get('from');
    var flights = this.get('model');

    if (from) {
      return flights.filterBy('from', from);
    } else {
      return flights;
    }
  }.property('from', 'to', 'model'),

  filteredFlights: function() {
    var to = this.get('to');
    var flights = this.get('filteredFromFlights');

    if (to) {
      return flights.filterBy('to', to);
    } else {
      return flights;
    }
  }.property('from', 'to', 'model')
});




Ember template not updating on changing properties

I have an Ember template which shows 5 divs by default. I have the template configured as follows-

<img class="col-lg-1  scroll-img" src="imgs/left_scroll_arrow.png" {{action 'active-credit-left-scroll'}}/>

    {{#each activebrand in limitedContent}}
               //HTML content
    {{#each activebrand in limitedContent}}




 <img class="col-lg-1 scroll-img scroll-right" src="imgs/right_scroll_arrow.png" {{action 'active-credit-right-scroll'}}/>

I am populating the template via my controller as follows:

export default Ember.Controller.extend({


    'activecreditstartVal':0,
     'activecreditendVal':5,
    actions:{

      'active-credit-left-scroll':function(){
         if(this.get('activecreditstartVal')>0){
           this.set('activecreditstartVal',this.get('activecreditstartVal')-1);
           this.set('activecreditendVal',this.get('activecreditendVal')-1);
         }
    },
     'active-credit-right-scroll':function(){
    this.set('activecreditstartVal',this.get('activecreditstartVal')+1);
        this.set('activecreditendVal',this.get('activecreditendVal')+1);


      },

    },
      limitedContent: function(){
        return this.get('model.firstObject.activebrands').slice(this.get('activecreditstartVal'),this.get('activecreditendVal'));
      }.property('model.firstObject.activebrands')


    });

Initially the filtering mechanism works and only records 0-5 are displayed, however on click of right scroll button I want to display records 1-6 . I checked that the values of activecreditStartVal and activecreditendVal are getting updated however the template is not getting updated.

What am I doing wrong? Thanks




Square: Is there a way to keep text in Description that does not get rendered at the store?

Is there a way to store a piece of text (8 to 12 chars) in Description or elsewhere that does not get rendered for the online store? Outside Description is OK, as long as this piece of text is accessible through ITEM_READ API (Get Items). I tried to wrap this text with HTML comments and that did not work.




samedi 27 juin 2015

EmberJS(without ember-cli) development behind firewall using systemjs or anyother loader

I am planning to use EmberJS for a small application in my day job. I have used a little ember on my laptop using ember-cli. However at work I don't have access to Github. I am planning to download the libraries and start using without any tools like npm, bower. I have tried to setup a static web app at http://ift.tt/1LCnKDy There is not much code in there. I have tried to keep the structure as close to ember-cli as possible, os that it will be easier for me to upgrade to ember-cli when access is availble. I would like to use ES6 modules like in ember-cli. However the fist step of loading the Ember is not working.

Error I see in chrome console is

Error: http://localhost:4200/vendor/ember/ember.debug.js detected as System.register but didn't execute.

Any help to resolve this appreciated. Thanks




Getting Django API data with Ember

I'm starting a project working with ember.js with Django Rest Framework for my REST Server.

I'm using an adapter on the ember side to get the data into the right format that Ember needs. I'm at the point where I'm making a request to my server, and getting a 200 with data returning, however Ember is throwing an error Error while processing route: index Assertion Failed: The response from a findAll must be an Array, not undefined.

There are quite a few posts about this error, but I haven't been able to find any that are relevant to my problem, it seems to be a sort of blanket error that can be caused by many things?

I'm at a loss because my server is receiving the request and returning data in the format that I would expect from the server. I'm not sure how to tell if the error is within my Ember app or if my data is not being transformed correctly by the adapter.

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

// config/environment.js
APP: {
  API_NAMESPACE: 'v1',
  ENV.APP.API_HOST = 'http://localhost:8000',
},

Just having this code in my router is how I get the error. I feel like this is a very simple problem, but can't seem to get past it. I've tried moving that code into different parts such as the controller, just to see that I can fetch data. Hopefully someone has a suggestion, thanks. Let me know anything else I can post to help.




Ember JS Enable dropdown only on element which was clicked

I am an Ember newbie and can't get my head around how to run events on specific elements populated via records on my ember model.

Here is my Template

{{#each user in model }}
  {{#each activecredit in user.activecredits}}
    <div class="col-lg-2 hive-credit-box active-credit">
        <div class="credit-brandname">
            {{activecredit.Brandname}}
        </div>
        <div class="credit-brand-image-container">

            <img src="http://localhost:3000/{{activecredit.Imglocation}}" class="credit-image"/>
        </div>

        <div class="hive-credit-percent"><img class="hive-filled-container" src="imgs/hivefilled9.png"/></div>
        <div class="hive-credit-dollars">$xx.xx</div>
        <div  {{bind-attr class=activecredit.Brandname}} {{action 'enableTrade'}}><img src="imgs/trade_button.png" class="credit-trade-button"  /></div>
        <div class="credit-brand-amount">
            xx%
        </div>

        <!-- Trade button click dropdown -->
       {{#if isSelected}}

        <div class="hivetrade">
            <div class="arrow_box">
                Hi there
            </div>
            <div class=""></div>
        </div>
        {{/if}}

    </div>
   {{/each}}
  {{/each}}

Now I want to show a drop down on each element on click of a button .

When I set the enableTrade action , all dropdowns of all the divs show up.

actions:{
  enableTrade:function(){
      this.set('isSelected',true);
  }
}

How do I enable only the dropdown in the particular div that was created.

I suppose I need to bind certain attributes to each div,but how do I access which div was clicked in my controller?

Any help would be appreciated . Thanks




Accessing precompiled component in Ember.js

I have my component precompiled using grunt-ember-templates and its now maintained inside the Ember.TEMPLATES collection as Ember.TEMPLATES["../components/course-details"]

The issue is I am not able to use that component in my view. For instance I have a view called IndexView and I am making use of template:Ember.TEMPLATES["../index"] in that view. Like this

  app.IndexView=Ember.View.extend({
    template:Ember.TEMPLATES["../index"]
})

The index Template is making use of the course-details component which is now precompiled and now I am not sure how I can pass the component Template in this view.




Custom sorting compare in Ember

I have a problem with sorting in Ember.

I use moment.js for handling all times in ember, I never use plain javascript date objects since I need to always be aware of timezone set by the user. When I do array.sortBy('datetime') and the properties for sorting are moment.js objects, sorting does not work, since compare method used by ember threat moment js as objects, thus returning 0. Is there any way to override default compare method as defined here - http://ift.tt/1eb11QS.

Since the method is included in mixins as Enumerable and others as closure and cannot be overridden afterwards.

Note: I don't want to use custom sorting like array.sort(function(a, b) ..., I want to use sortBy and have compare function handle the logic behind the curtain.

Thanks in adance




setting which controller to handle a certain action

I'm using the structure of the Ember version of the TodoMVC app for an Ember app by which I mean that, after setting the application route to products

export default Ember.Route.extend({
    redirect: function(){
        this.transitionTo('products');
    }
});

I then use the ul structure of the todo app, with each product occupying a new list position (as each todo does in the TodoMVC). I also (as with the Todo app) bind some attributes that allow me to set css styles depending on state

<ul id="products">  

            {{#each product in products }}

                <li {{bind-attr class="isEditing:editing"}}> 

Depending on state, an input box will be visible for a product once a user clicks a button. The problem is that once the user clicks the button, isEditing is set to true for all the products, so all the input boxes are visible. The action (which makes the input box visible) is handled on the products controller

showInput: function(item){
    this.set('isEditing', true);
},

I only want the input box made visible for the particular product where the click event was triggered. In the Todo MVC app, the action to make the input field visible is handled on a (singular) Todo controller, not the TodosController, so in my app, I created a (singular) product controller and put the action there but when the user clicks the button on an individual product in the list, the action on the (single) product controller is not triggered. How can I get the product controller to handle the action, or alternatively, ensure that only one input field is made visible.

You can see how the functionality is supposed to work on the live demo the TodoMVC app by creating a few todo items and then clicking on one of them. Only one input field becomes visible.




Cannot access to parent model from child view

I have a problem with my emberjs view. I cannot access to the model defined in the parent view. I have tested with view.parentView.model and this not working

Here is my code :

<div class="allowed_name">{{model.allowed_email_domain}}</div><!-- working -->
{{#each view.content}}
  <h1>{{model.allowed_email_domain}}</h1> <!-- not working -->
{{/each}}

Thank's




Remove a sticky parameter

I have an application which displays flight information. All list of all flights is available via http://localhost:4200/flights and a list of all flights from Frankfurt via http://localhost:4200/flights?from=FRA

Below the displayed list are two links for the user to toggle between the views. Unfortunately once a user clicked on the http://localhost:4200/flights?from=FRA link he/she has no way of going back to http://localhost:4200/flights via clicking on the corresponding link. The from=FRA parameter is sticky.

How can I link to the http://localhost:4200/flights page and get rid of the from=FRA parameter?

The code I use:

app/templates/flights.hbs

<ul>
{{#each flight in filteredFlights}}
  <li>{{flight.code}} {{flight.from}} - {{flight.to}}</li>
{{/each}}
</ul>

<ul>
  <li>{{#link-to 'flights'}}All flights{{/link-to}}</li>
  <li>{{#link-to 'flights' (query-params from="FRA")}}Flights from Frankfurt{{/link-to}}</li>
</ul>

app/controllers/flights.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['from','to'],
  from: null,
  to: null,

  filteredFromFlights: function() {
    var from = this.get('from');
    var flights = this.get('model');

    if (from) {
      return flights.filterBy('from', from);
    } else {
      return flights;
    }
  }.property('from', 'model'),

  filteredFlights: function() {
    var to = this.get('to');
    var flights = this.get('filteredFromFlights');

    if (to) {
      return flights.filterBy('to', to);
    } else {
      return flights;
    }
  }.property('from', 'to', 'model')
});

app/routes/flights.js

import Ember from 'ember';

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




Importing Bourbon with broccoli-sass

I have installed Bourbon with Bower, but cannot get broccoli-sass to import Bourbon. Broccoli-sass is compiling my app.scss file to app.css.

I have tried

@import '_bourbon';

and

@import 'bourbon';

at the top of my app.scss file but get the error:

Error: file to import not found or unreadable: _bourbon

My brocfile:

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

var app = new EmberApp();

var sassImportPaths = [
  'app/styles',
  'bower_components/bourbon/app/assets/stylesheets',
];

var appCss = compileSass(sassImportPaths, 'app.scss', '/assets/app.css');


module.exports = app.toTree([appCss]);




Ember: Inserting 100 components, and setting an attribute for each

I'm playing with creating a drag and drop feature. I'm trying to create a grid, to drag elements onto, and then carry out some action based on the drop element.

I've created components for dragging and dropping. To create the grid, I want to insert a couple of hundred or so of the droppable components, and give each one a unique number I can use inside the components template.

How should I insert 100 elements and give the unique attribute to each?

Thanks




Jquery initialization in nested components with async loading

I have an album component that then uses a bunch of image components for each image in the album. After the album is inserted it calls a lightbox function to lightbox the images. This is done on the parent element of the images to make you able to swipe and such between images. This works perfectly in the didInsertElement function of the album component when you go to the url of the album itself as the data from the backend is available as nested data in the album itself.

However, when I then show a list of albums and a user clicks one to show that particular album, the data for the images is loaded in an async fashion. This means that the didInsertElement event will fire before the images are available and thus the lightboxing doesn't work properly as the images don't exist in the dom yet.

What do you do in this case?




How to store the user id in session with ember-simple-auth?

I want to store the user id in the session. I have this authenticate method in a custom authenticator :

authenticate: (credentials) ->
  _this = this
  new (Ember.RSVP.Promise) (resolve, reject) ->
    Ember.$.ajax(
      url: 'http://localhost:3000/api/v1/sessions'
      type: 'POST'
      data: session:
        email: credentials.identification
        password: credentials.password
    ).then ((response) ->
      _this.set('user_id', response.user_id)
      Ember.run ->
        resolve token: response.token
    ), (xhr, status, error) ->
      response = JSON.parse(xhr.responseText)
      Ember.run ->
        reject response.error

It's coffee script but it works like javascript. As you can this, I set 'user_id' in the session.

In app/initializers/custom-session, I have this :

import Ember from "ember";
import Session from "simple-auth/session";

export default {
  name: "current-user",
  before: "simple-auth",
  initialize: function(container) {
    Session.reopen({
      setCurrentUser: function() {
        return this.get('user_id')
      }.observes('secure.access_token')
    });
  }
};

user_id always returns undefined. I found many solutions on the Internet but nothing works.

Is there a simple solution to do that?




What should I use instead of DS.FixtureAdapter

You gotta love ember.js team... I'm getting this depreciation message saying that: "DS.FixtureAdapter has been deprecated and moved into an unsupported addon: http://ift.tt/1e9rbDC". Guys maintaining that addon advise that we should use a library similar to Pretender. Has anybody done that? Is there a tutorial showing how to integrate this lib so that everything would work as before?




How to read parameters from the URL and search for it?

I have an index of all flights that is displayed at http://localhost:4200/flights

How can I create a Kayak like experience where the URL http://localhost:4200/flights/FRA-JFK would display only the flights from FRA to JFK?

The setup:

ember new travel_app
ember g http-mock flight
ember g adapter application
ember g resource flights

app/models/flight.js

import DS from 'ember-data';

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

app/routes/flights.js

import Ember from 'ember';

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

app/templates/flights.hbs

List of flights:

<ul>
{{#each flight in model}}
<li>{{flight.code}} {{flight.from}} - {{flight.to}}</li>
{{/each}}
</ul>

server/mocks/flights.js

module.exports = function(app) {
  var express = require('express');
  var flightsRouter = express.Router();

  var items = [
    {
      id: 1,
      from: "FRA",
      to: "JFK",
      code: "LH 400"
    },
    {
      id: 2,
      from: "JFK",
      to: "FRA",
      code: "LH 401"
    }
  ];

  flightsRouter.get('/', function(req, res) {
    res.send({
      'flights': items
    });
  });

[...]

app/adapters/application.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  'namespace': 'api'
});




Pass property to component and then used it as conditonal (ember js)

application controler

isHotel_profile: function (){
    return this.get('currentPath') === 'hotel';
}.property('currentPath'),

component

{{#step-controller hotelPage=isHotel_profile}} {{/step-controller}}

and here's the component template

{{#if hotelPage}}
 hotel page 
{{else}}
 not hotel page
{{/if}}

i want to use the property as conditional how can i achieve that




vendredi 26 juin 2015

Showing 'item' route on Ember.js modal

How would you achieve something like Pinterest does with there modal? You can have the same 'pin' modal over multiple different urls. e.g. index, user profiles, categories and so on. The reason is that I want to have the 'item' modal in the URL is so that people can bookmark it or share the link, that gets them to the dedicated 'item' route that is shareable.

Would using beforeModel be ideal? I'm a bit lost as to how to use this type of UI.




Ember Data has undefined properties from JSON API response

Ember and javascript newbie. Sorry.

ember.debug.js:5361DEBUG: Ember      : 1.13.2
ember.debug.js:5361DEBUG: Ember Data : 1.13.1
ember.debug.js:5361DEBUG: jQuery     : 1.11.3

I'm using ember-json-api,

npm install --save-dev ember-json-api

"ember-json-api": "^0.5.0",

I've set up the adapter, adapter/application.js

import JsonApiAdapter from 'ember-json-api/json-api-adapter';

export default JsonApiAdapter.extend({
    namespace: "api"
});

I've set up the serializer, serializer/application.js

import JsonApiSerializer from 'ember-json-api/json-api-serializer';
export default JsonApiSerializer;

I've set up a model, models/competitions.js

import DS from 'ember-data';

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

I've set up a mock, server/mocks/competitions.js

 competitionsRouter.get('/', function(req, res) {
    res.send({
      "data": [
          {
              "type": "competition",
              "id": "10",
              "attributes":
                  {
                      "ord": 1,
                      "name": "Competition Mock 2015",
                      "imageUri": "http://localhost/Pictures/1"
                  }
          },
          {
              "type": "competition",
              "id": "11",
              "attributes":
                  {
                      "ord": 2,
                      "name": "Competition Mock 2014",
                      "imageUri": null
                  }
          }
      ]
  });

When I call my competitions route the ember inspector is displaying in the data section that there are two competition objects and it correctly displays their Id values of 10 & 11 but the name, imageUri and ord properties are all listed as undefined.

Is my mock returning the data in the correct format? If so, what am I missing ?




Error with get('model').addObjects() in Ember 1.13.0

I'm upgrading an Ember application from 1.11 to 1.13.2

I've got a blog initially displaying 5 blog-entries. They are loaded in the model with this route:

import Ember from 'ember';
export default Ember.Route.extend({

  model: function() {
    return this.store.find('post', {limit: 5});
   }
});

There's a button to load more entries in the controller:

loadMore: function() {
  var self = this
  this.store.find('post', {limit: 5,
                           skip: 5})
    .then(function(posts) {
      self.incrementProperty('page');
      self.get('model').addObjects(posts);
    });
}

However since upgrading I get this error after loadMore was executed:

TypeError: internalModel.getRecord is not a function
    at Ember.ArrayProxy.extend.objectAtContent (record-array.js:84)
    at _emberRuntimeSystemObject.default.extend.objectAt (ember.debug.js:35919)
    at _emberRuntimeSystemObject.default.extend.objectAtContent (ember.debug.js:35780)
    at _emberRuntimeSystemObject.default.extend.objectAt (ember.debug.js:35919)




Accessing different model from router in ember cli

I have established two models with Has Many relationship

// app/models/userwelcome.js
export default DS.Model.extend({
  favorites:DS.hasMany('favorite'),
  brandcredits:DS.attr(),
  token: DS.attr('string'),
  fullname:DS.attr('string'),
  userimglocation:DS.attr('string'),
  city:DS.attr('string'),

 });

and

// app/models/favorite.js
export default DS.Model.extend({

  Brandname: DS.attr('string'),
  Imglocation: DS.attr('string'),
  Checked:DS.attr('string'),
  Createdate:DS.attr('date'),
  userwelcome: DS.belongsTo('userwelcome')

});

I am leading the records via a sideloaded json from my server as follows-

{ userwelcome: 
   [ { _id: 558ce2af106319b412e48b67,
       userimglocation: '/images/user_imgs/ppl5.jpg',
       city: 'Mountain View',
       fullname: 'Sansa Stark',
       favorites: 
        [ '5586da238a60ebcb7abeb733',
          '5586da128a60ebcb7abeb732',
          '558b382e7881f424154d6c27',
          '558b38467881f424154d6c28',
          '558b38687881f424154d6c29' ],
       brandcredits: 
        [ { brand_id: '5586da128a60ebcb7abeb732',
            brand_credits: 123,
            _id: 558ce2af106319b412e48b6c },
          { brand_id: '5586da238a60ebcb7abeb733',
            brand_credits: 500,
            _id: 558ce2af106319b412e48b6b },
          { brand_id: '558b382e7881f424154d6c27',
            brand_credits: 500,
            _id: 558ce2af106319b412e48b6a },
          { brand_id: '558b38467881f424154d6c28',
            brand_credits: 500,
            _id: 558ce2af106319b412e48b69 },
          { brand_id: '558b38687881f424154d6c29',
            brand_credits: 245,
            _id: 558ce2af106319b412e48b68 } ] } ],
  favorite: 
   [ { _id: 5586da128a60ebcb7abeb732,
       Checked: false,
       Imglocation: '/images/banana.png',
       Createdate: 'Sun Jun 21 2015 08:36:50 GMT-0700 (PDT)',
       Brandname: 'Banana Republic',
       __v: 0 },
     { _id: 5586da238a60ebcb7abeb733,
       Checked: false,
       Imglocation: '/images/gap1433683451312.png',
       Createdate: 'Sun Jun 21 2015 08:37:07 GMT-0700 (PDT)',
       Brandname: 'GAP',
       __v: 0 },
     { _id: 558b382e7881f424154d6c27,
       Checked: false,
       Imglocation: '/images/hugoboss1433683671484.png',
       Createdate: 'Wed Jun 24 2015 16:07:26 GMT-0700 (PDT)',
       Brandname: 'Hugo Boss',
       __v: 0 },
     { _id: 558b38467881f424154d6c28,
       Checked: false,
       Imglocation: '/images/levis1433683501618.png',
       Createdate: 'Wed Jun 24 2015 16:07:50 GMT-0700 (PDT)',
       Brandname: 'Levis',
       __v: 0 },
     { _id: 558b38687881f424154d6c29,
       Checked: false,
       Imglocation: '/images/lululemon.jpg',
       Createdate: 'Wed Jun 24 2015 16:08:24 GMT-0700 (PDT)',
       Brandname: 'Lulu Lemon',
       __v: 0 } ] }

The records are getting loaded but I want to know how to access data from model favorite in my userwelcome route. I am setting my userwelcome route as follows-

  model: function() {
   var token=this.controllerFor('index').get('token');

    console.log(token);

    var self=this;

    var inflector = Ember.Inflector.inflector;
    inflector.irregular('userwelcome', 'userwelcome');
      return this.store.find('userwelcome',{'token':token});


  }

I am able to access fields from userwelcome model but how do I access fields from favorite model?

Thanks




ObjectAt(0) doesn't work with Ember.Controller

I'm trying to upgrade my Ember application to the latest Ember 1.13.2 and therefore am trying to replace all Ember.ArrayController with Ember.Controller.

I've got a problem with the category-controller of my blog. The data retrieved from my server looks like this:

 "posts": [
    {
      "category": {
         "id": "1",
         "name": "tech"}
      "title": "my title",
      "body": "post-content",
      "isPublished": true,
    },
   ...
   ]

In my category-controller I need both, the category-id and the category-name.

With the Ember.ArrayController I used objectAt(0) to get both from the first post loaded in the model for that purpose but this doesn't work with Ember.Controller anymore.

How can I get these two attributes in my controller?

This code doesn't work anymore:

  breadCrumb: function(){
    return this.objectAt(0).get('category').get('name');
  }.property('model.[]'),

  categoryId: function(){
    return this.objectAt(0).get('category').get('id');
  }.property('model.[]'),




Using the result of a promise in Ember.RSVP.hash

I've been pulling out my hair with this for a few hours now so I thought I'd just ask :)

In a route, I'm grabbing the account ID from the session store:

var accountId = this.get('session.currentUser').then(function(user) {
  return user;
}).then(function(user) {
  return user.get('account');
}).then(function(account) {
  var accountId = parseInt(account.get('id'));
  console.log(accountId); // outputs 2
  return accountId; 
});

I'm also returning an Ember hash of layouts using a (presently) hard-coded ID:

return Ember.RSVP.hash({
  layouts: this.store.query('layout', { account_id: 2 }) 
});

/* {{log layouts}} in the template returns the correct list of layouts */

However, when I try and use the value of the first promise in the hash, as follows:

return Ember.RSVP.hash({
  layouts: this.store.query('layout', { account_id: accountId })
});

I get the following error:

You must pass a resolver function as the first argument to the promise constructor

TypeError: You must pass a resolver function as the first argument to the promise constructor

I can almost understand this, as perhaps the accountID promise isn't resolved before the hash function is called.

But then I tried:

var _this = this;
var accountId = this.get('session.currentUser').then(function(user) {
  return user;
}).then(function(user) {
  return user.get('account');
}).then(function(account) {
  var accountId = parseInt(account.get('id'));
  console.log(accountId); // outputs 2
  return accountId;
}).then(function(accountId) {
  console.log(accountId); // outputs 2
  return Ember.RSVP.hash({
    layouts: _this.store.query('layout', { account_id: accountId })
  });
});

This does not give any errors, but {{log layouts}} in the template returns 'undefined'.

Can anyone help, please?




Rendering hundreds of datas : lazy loading, partial rendering?

I can seem to find a good answer for my problem. I have a sidebar template which contains a div for each item my model contains. When I have hundreds of items to render, it takes up to 8-10 seconds to render the template. I am using ember-data.

How can I render the items that are loaded before it finishes fetching the entire model?

Here is my template :

{{#each conv in model itemController='singleconv'}}
        {{#if (equals conv.url selectedSubuserEmail)}}
            <div class="conversation-content-wrapper" {{action "clickConv" conv preventDefault=false}}>
                    <div class="history-message-assigned in-progress-closed" style="display:none;"><p><i class="icon-x"></i>Conversation closed</p></div>
                    <div class="history-message-assigned in-progress-assignation" style="display:none;"><p><i class="icon-assign"></i>Conversation assigned</p></div>
                    <div class="history-message-assigned in-progress-reopen" style="display:none;"><p><i class="icon-re-opened"></i>Conversation re-opened</p></div>          
                <div class={{conv.selectedClass}}>          
                    <div class="conversation-time-history">{{{conv.status}}}</div>
                    <div class="conversation-details">
                        <span class="unread-numbers"></span>
                            {{input type='checkbox' class='chk-conversation' checked=conv.isChecked}}
                             <span class="conversation-name">{{conv.customer.name}}</span>
                             <span class="phone-number">{{conv.customer.cellPhoneNumber}}</span>
                            <p class="conversation-text">{{conv.lastMessage}}</p>
                    </div>
                </div>                       
            </div>
        {{/if}}
{{/each}}




Ember render not calling parent component

When a component is rendered inside an outlet from the app route it is not calling(may be not even creating an instance) of PARENT component. Whereas if its rendered inside a template it works fine. Please see the JS Bin below, its self evident.
JS Bin for problem . First it renders inside a template, click on show modal and you will see the issue.

Not sure if i am doing something wrong here. Thanks in advance.




Ember: Dynamically created component actions don't fire

I'm having trouble with {{actions}} on Ember (1.11.0) components not being triggered when the component has been added to the page dynamically. Oddly enough, it seems to be related to how the ember application has been added to the page - via the default template vs. added to a "rootElement".

Working JSBin: actions are triggered

Non-Working JSBin: actions aren't triggered

My Component Definition:

<script type="text/x-handlebars" data-template-name="components/foo-bar">
    <p>Component {{name}}</p>
    <button {{action "doIt"}}>Do It</button>  
</script>

App.FooBarComponent = Ember.Component.extend({
    click: function() {
        console.log('click fired! - ' + this.get('name'));
    },
    actions: {
        doIt: function() {
            console.log('doIt fired! - ' + this.get('name'));
        } 
    }
});

The click() event and doIt() action aren't triggered when the component has been added to the page dynamically. I'm using append() method to add the component to the page:

App.IndexController = Ember.Controller.extend({
    count : 1,
    actions: {
        createNewFoobBar: function() {
            this.set('count', this.get('count') + 1);
            var comp = this.container.lookup('component:foo-bar');
            comp.set('name', this.get('count'));
            comp.set('controller', this);
            comp.append();
        }
    }
});

In either case, actions are properly triggered when the component is part of the template:

{{foo-bar name="one"}}




ember-i18n : TypeError: app[initializerType] is not a function

I've been installing ember-i18n on a working Ember project. (http://ift.tt/1kRLqqq)

After registering an initializer app/initializers/i18n.js :

export default {
  name: 'i18n',

  after: 'ember-i18n',

  initialize: function(_, app) {
    app.inject('model', 'i18n', 'service:i18n')
  }
};

And relaunching the server, I get this error in the console :

app[initializerType] is not a function

Do you have any idea ?




Stop changes propagation until save button is clicked in ember.js

My desired scenario is that the value entered into a bound input field shouldn't propagate to the model until save button is clicked. I found this topic: Emberjs: Prevent changes propagation throughout a transaction however it's quite old. Is there another way to accomplish this?




jeudi 25 juin 2015

ember.js runtime resolver not working

I'm new to ember.js (but I know MVC from my CakePHP experiences and JS as well) and in the last 2 weeks I build a little app at work which loads sideloaded JSON data with the REST-Adapter. I added some buttons with actions and everything works fine and I learned a lot, but it takes time to figure out the details.

All my controllers, routes and models are not organised at the moment in a folderstruture which is described in the ember.js-Guide: http://ift.tt/1fIkmtN

Now I want to move the files to the folderstructure. But then the application does not work. It seems to my that the resolver can not finde the files at runtime. But why?

An easy example which does not work:

in "app.js" (loaded with -tag in "index.html"):

App = Ember.Application.create({
    LOG_RESOLVER: true // just for debugging
});

in "router.js" (loaded with -tag after "app.js" in "index.html"):

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

in "routes/mytest.js":

export default Ember.Route.extend({
  setupController: function(controller) {
    controller.set('title', "Hello world!");
  }
});

in "controllers/mytest.js":

export default Ember.Controller.extend({
    appName: 'mytest'
});

in "indes.html":

<script type="text/x-handlebars">
    {{#link-to 'mytest' }}Mytest{{/link-to}}<br/>
    {{outlet}}
</script>
<script type="text/x-handlebars" id="mytest">
  mytest Template
  <h1>appName: {{appName}}</h1>
  <h2>title: {{title}}</h2>
</script>

The Handlebar-template "mytest" is showen, but {{appName}} and {{title}} are empty. If I moved the "mytest"-Template to "templates/mytest.hbs" nothing is showen.

Seems to my that the resolver does not work. Or something wrong with the naming-conventions Guide?

My another assumption: Resolver-Stuff only works when using a buildprocess like in ember-cli.

Using "ember-1.12.1.debug", "ember-template-compiler-1.12.1"

Thanks for help.