jeudi 30 avril 2015

Ember-cli unit test using ember-cli-simple-auth

I'm trying to write a unit test for a controller that uses simple-auth authentication in an ajax call. Assertion tests work great but the session property does not appear to be defined in the unit test module scope.

Example action in controller:

authenticate() {
  let credentials = this.getProperties('identification', 'password');
  this.get('session').authenticate('simple-auth-authenticator:token', credentials)
    .then(() => {
      this.transitionToRoute('index');
    }, (error) => {
      this.set('errorMessage', error.error);
    });
}

Example test:

it('should not authenticate', function () {
  let controller = this.subject();
  controller.send('authenticate');
  expect(controller.get('errorMessage')).to.equal("Invalid email/password combination");
});

Session is undefined error message:

TypeError: Cannot read property 'authenticate' of undefined
at authenticate (http://localhost:7357/assets/app.js:587:28)
at mixin.Mixin.create.send (http://localhost:7357/assets/vendor.js:37164:54)
at Context.<anonymous> (http://localhost:7357/assets/app.js:2002:18)
at Context.wrapper (http://localhost:7357/assets/test-support.js:1756:27)
at invoke (http://localhost:7357/assets/test-support.js:13772:21)
at Context.suite.on.context.it.context.specify.method (http://localhost:7357/assets/test-support.js:13837:13)
at Test.require.register.Runnable.run (http://localhost:7357/assets/test-support.js:7064:15)
at Runner.require.register.Runner.runTest (http://localhost:7357/assets/test-support.js:7493:10)
at http://localhost:7357/assets/test-support.js:7571:12
at next (http://localhost:7357/assets/test-support.js:7418:14)




Ember infinite loop in rails api when updating record

I am trying to update a user using embers rest adapter and a rails api,

Every works until the user obj is processed by rails, there as infinite request loop from ember for updating and getting the updated user obj?

Please help, also I'm new to ember so if anyone spots anything that should be address, let me know... Primarily I need to get this fix. It's driving me insane.

SHOW CONTROLLER / EDIT USER FROM HERE

 export default Ember.Controller.extend({
    needs: ['application'],
    actions: {
        editUser: function() {
           var appCtrl = this.get('controllers.application');
           return appCtrl.set('confirmPassword', true);
       }
   },
   currentUser: function() {
       return this.get('controllers.application.currentUser');
   },
   passwordConfirmed: function() {
       var _this = this;
       var passwordEntered = this.get('controllers.application.passwordEntered');
       if (passwordEntered) {
           this.currentUser().then(function(user) {
               user.setProperties({
                   name: _this.get('name'),
                   email: _this.get('email'),
                   avatar: document.getElementById('file-field').files[0],
                   password: passwordEntered.password,
                   password_confirmation: passwordEntered.password
               }, null);
               user.save();
           });
       }
   }.observes('controllers.application.passwordEntered')
  });

USER MODEL

import DS from 'ember-data';

    export default DS.Model.extend({
         name: DS.attr('string'),
         email: DS.attr('string'),
         username: DS.attr('string'),
         avatar: DS.attr('file'),
         thumb: DS.attr('string'),
         password: DS.attr('string'),
         password_confirmation: DS.attr('string'),
         user: DS.hasMany('brands', {
         async: true
     });
});

APPLICATION CONTROLLER

import Ember from 'ember';

export default Ember.Controller.extend({
     needs: ['users/show'],
     confirmPassword: false,
     passwordEntered: false,
     actions: {
         invalidateSession: function() {
              this.authManagerService.endSession(this);
         },
         submitPassword: function() {
             var password = this.getProperties('password');
             this.set('passwordEntered', password);
             this.set('confirmPassword', false);
         },
         closeModal: function() {
             this.set('confirmPassword', false);
         }
     },
     currentUser: function() {
         if (this.session.get('user_id')) {
             return this.store.find('user', this.session.get('user_id'));
         }
     }.property('this.session.isAuthenticated'),
     removeMessage: function() {
          if (Ember.$('.message')) {
               this.set('messages', this.messages);
          }
          Ember.run.later(function() {
              Ember.$('.message').remove();
          }, 2000);
      }.observes('messages') 
 });




Ember get the JSON response of a POST request

I have a Ruby On Rails API and a front end in ember apart. I'm trying to add a record from ember to my api. I can see in my api logs that my request is well executed and return a json. But in my ember app i try to print that JSON response and access to those informations..

here's the code from my controller to create a record from my ember app :

export default Ember.Controller.extend({
  actions: {

    submit: function(){
      var result = this.store.createRecord("session", {email: this.get('email'), password: this.get('password')});
      var onSuccess =  function(post){

        console.log("kikou");
        console.log(post);
      };

      var onFail =  function(post){
        console.log("kikou");
        console.log(post);
      };

      result.save().then(onSuccess, onFail);
    }
  }

the JSON returned is :

{"user":{"email":"gui@hotmail.com","authentication_token":"4vLAkiM1Ro5qN2HeNogM","id":1}}

How can I access to email, authentication_token etc...? Maybe I'm doing something wrong or it is not the proper way to create a record on my rails api?

I do not want to make any ajax code in my controller otherwise I do not see any interest to use Ember.

Thank you for your help,




In an Ember Array, how do i access object by index value? Ember Js

For an ember array you can simply do this:

array.get('firstObject');

to get the first object in array.

or this:

array.get('lastObject');

to get last object in array.

How do I get something by its index? similar to how it works in an ordinary javascript array:

array[index];




How do I return the result of Ember.RSVP.all from a function?

The function below needs to return a true or false. Inside the then call at the bottom of the function, I get the value I need from result.isAny('hasOverride') but I don't know how to return this value from the hasRoomUpcharge function. How do I do this? I thought adding return in front of Ember.RSVP.all would do it, but it doesn't work. Please help!

hasRoomUpcharge: function(roomRates, defaultRoomTypeCode){
    var defaultRoomRates = roomRates.findBy('roomTypeCode', defaultRoomTypeCode);
    var nonDefaultRoomRates = roomRates.rejectBy('roomTypeCode', defaultRoomTypeCode);
    var nonDefaultRoomMasters = this.modelFor('propertyPricing').roomTypeMasters.rejectBy('isDefault');

    var promises = [];
    var promise;

        nonDefaultRoomMasters.forEach(function(roomMaster){
            var roomTypeCode = roomMaster.get('roomTypeCode');

             promise = roomMaster.get('roomRateUpcharge').then(function(roomRateUpcharge){
                var currentRoomMasterOnePersonPrice = nonDefaultRoomRates.findBy('roomTypeCode', roomTypeCode).onePersonPrice;
                var defaultRoomMasterOnePersonPrice = defaultRoomRates.onePersonPrice;
                var roomUpcharge = roomRateUpcharge.get('onePersonRateUpcharge');

                if(currentRoomMasterOnePersonPrice != defaultRoomMasterOnePersonPrice + roomUpcharge){
                    return { hasOverride: true };
                }
                else {
                    return { hasOverride: false };
                }
            });

            promises.push(promise);
        });


        return Ember.RSVP.all(promises).then(function(result){
            return result.isAny('hasOverride');
        });
},




EmberJS / Select / Content (list) / Selection / Object Equality / Compare (comparison)

I have a route like this:

ConsultasRoute = Em.Route.extend({
  model: function() {
    return Em.Object.create({
      tipoClave: undefined,
      tipoConsulta: {id: 2, nombre: 'yow man'}
    });
  }
});

I have a controller like this:

ConsultasController = Ember.ObjectController.extend({
  tipoConsultas: [{id: 1, nombre: 'dudeee'}, {id: 2, nombre: 'yow man'}] 
});

And a template like this:

{{view 'select' content=tipoConsultas selection=model.tipoConsulta optionValue="content.id" optionLabelPath="content.nombre" prompt="Selecciona tipo consulta"}}

The idea is: by default the selected tipo consulta is "yow man".

But this does not work; "yow man" is not selected by default.

I think object-equality thing is in the play here. How to tell ember to do object-equality check using specific property of an object (e.g.: the "id") ?

I read about this Comparable Mixin: http://ift.tt/1ph7Zms maybe this can help (?). But I can't find an example of its correct use anywhere.

Can someone show me how to solve this?

Thanks in advance, Raka




Get value from emberjs form

I'm a newbie with Emberjs and I need some advices.

I try to use this addon http://ift.tt/1s8q7EZ

So I have created my form :

 {{#em-form model=sessions submit_button=false}}
    {{em-input property="email" type=email label="Email" placeholder="Entrer votre email..."}}
    {{em-input property="password" type="password" label="Mot de passe" placeholder="Enter votre password..."}}
    <div class="form-actions">
      <input {{bind-attr disabled=isntValid}} type="submit" class="btn btn-primary" value="Se connecter">
    </div>
 {{/em-form}}

so I have a controller to catch the submit action :

export default Ember.Controller.extend({
 actions: {
  submit: function(){
   alert(this.get('sessions.email'));
  }
 }
});

My question is just I don't get it to how print my value from my form? I try this.get('email') or this.get('sessions.email') but always got an undefined in my alert box

Any help would be great! Thanks!




Authentication Strategy using Torii for Ember CLI 'static' apps

Just to clarify my understanding of what Torii provides for client side static apps:

  • OAuth 2.0's Implicit Grant workflow is the only OAuth workflow which works in client side static apps.

  • Torii only supports this via torii/providers/oauth2-bearer, which returns tokens not codes.

  • If 1. and 2. are true, then I suppose all client side static apps which use Torii would only use the oauth2-bearer approach. The rest of the providers in Torii, like stripe-connect etc. which are code workflow based would need server support to get an AccessToken based on the code.

Is this right?

Thanks in advance.




How to change the content of div on the basis of what is selected in the menu

Please bear with me, this question is very crude. I'm new to Ember js, and have got a lotta confusion between views controllers templates routes. I have this basic requirement, to have a menu on the left, with item users, organizations. and a div in the center, As of now, when i click users, i have given a link to /users route. for organizations /organizations route, which is a different template. I want to display them in the centered div. Not sure how to do that. I think it has got something to do with child views, but find myself numb in beginning. I just need help in the workflow of how to achieve this.




Preferred Ember Data URL and JSON structure for multi-word models

If I have an Ember model named DatabaseType, and want to use it with a REST adapter for Ember Data (I control the server-side API), what should the API URL look like, and what does Ember Data expect the payload to look like, in terms of CamelCase vs snake_case/underscore, and in terms of pluralizing?

Given that the recommended REST URL structure for multiple words is to use underscores (and not camel case), but also given that Ember Data is picky and opinionated about naming conventions and payload structure:

A. Should the API endpoint be:

  1. CamelCase - /databaseTypes/1/

  2. snake_case - /database_types/1/

B. What should the payload JSON root be?

  1. Get database types -> { databaseTypes: [ ... ] }

  2. Get database types -> { database_types: [ ... ] }




with ember cli, how to specify different layout for a component within POD structure

I have a a basic ember cli app with a component, and I wanted to specify different layoutName to the component based on a property passed to it. I am not sure how to achieve this. Right now I just want to know how to specify a templateName to a known template to get started. This is what I tried:

import Ember from 'ember';

export default Ember.Component.extend({

    layoutName: null,

    initialize: function() {
        this.set('layoutName', 'pi/pods/components/questions/single-select/standard-layout');
    }.on('init')

});

and my folder structure looks like:

app
|-pods
    |-components
              |-questions
                    |-single-select
                            |-component.js
                            |-template.hbs//just has {{yield}}
                            |http://ift.tt/1Jc4vMU hello

JUST A THOUGHT : This may be a new question itself - before we used jsbin to collaborate but now how can we achieve same when we are building stuff with ember-cli!!




Create loading substate for application

I'm trying to create a loading substate for the Application route using the new named substate options added recently, but for some reason, I can't get it to work. Originally, I just had created a simple template, loading.hbs, and it worked automatically, but because of the issues with substates on the application route, some of my UI was still visible. I'd like to correct this now.

I've tried renaming and moving the template around to the following places:

/templates/application_loading.hbs 
/templates/application-loading.hbs
/templates/application/loading.hbs

None seem to work though. I don't need any custom routing behavior so the default generated route should do me, unless its a requirement for this to work. Documentation on this feature seems to be sparse.

Thank you for any assistance.




Whats the best database to use with ember cli

I am wondering what is the best database to use for ember cli (ember.js). MongoDB looks like its a hazzle with the id, parse was also not that convincing.

Anybody some suggestions?

Greetings




Ember-cli two applications in one

I build chat application with Ember for desktop version of site. After that I deceided to create mobile version of site using Ember. Differnce that in mobile site I use locationType: 'auto' but chat needs locationType: 'hash' and different because it builds in page. For that I forked ember-cli and made changes http://ift.tt/1JbQEGm

But I don't like this solution. Please advise something.




Getting proper data model when rendering into outlet in Ember

I am trying to create a select box in a modal that has a list of all cars in inventory. If I enter the app from a page that has all the data loaded and open the modal it works correctly. However if I am on a route that doesn't have the data loaded, then open the modal the select options do not show. Furthermore the options will never update from that point. How do I get the proper model data to load? Please be easy on me, I have less than a year of programming experience, and thanks for the help.

Dms.SellDialogController = Ember.ArrayController.extend({
  cars: function() {
    return this.store.find('car').filterProperty('isSold', false);
  }.property('model'),
  selectedCar: '',
  carObjects: function() {
    var cars = this.get('cars').map(function(car) {
      return obj = {id: car.get('id'), key: car.get('keyNumber'), label: 'KEY#:'+car.get('keyNumber') + ' - STOCK#:' + car.get('stock')+' '+car.get('year')+' '+car.get('vModel')};
    });
    cars.sort(function(a, b){return a.key-b.key;})
    return cars;
  }.property('route'),
  title: 'Select the car you are selling'
});

ApplicationRoute... ...

openModal: function(modalName, model) {
  this.render(modalName, {
    into: 'application',
    outlet: 'modal',
    model: model
  });
},

Action to open modal inside application template

{{action 'openModal' 'sellDialog' model}}

and the templates

<script type="text/x-handlebars" id="components/modal-dialog">
  <div class='modal-overlay' {{action "closeModal" target=cntrllr}}>
    <div class='modal' {{action "dngn" target=cntrllr bubbles=false}}>
      <div class='modal-content'>
        <div class='modal-header'>
          <button type="button" class="close" aria-label="Close" {{action "closeModal" target=cntrllr}}><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">{{title}}</h4>
        </div>
        {{yield}}
      </div>
    </div>
  </div>
</script>
<script type="text/x-handlebars" data-template-name="sellDialog">
  {{#modal-dialog title=title cntrllr=controller model=model}}
    <div class="modal-body">
      <span class='pull-left'>Key Number: 
        {{view "select" content=carObjects optionValuePath="content.id" optionLabelPath="content.label" selection=selectedCar}}
      </span>
    </div>
    <div class="modal-footer">
       <button {{action "modalAction" controller "sell" selectedCar.id}}>Sell</button>
       <button {{action "closeModal"}}>Cancel</button>
    </div>
  {{/modal-dialog}}
</script>




I'm looking for a client-facing framework for a web application - what should I use?

I am a junior front end developer and am having some trouble choosing the appropriate client-facing framework for an upcoming project.

Without going into too much detail, the project is for a coupons website. The site will have multiple pages listing coupons and other deals. On the server side my team member is creating a Laravel REST API, which will send the relevant data to the client as JSON.

On the client, we really just need view templates to show that data. There will also be basic community features like commenting. Based on this information, is there any framework that might be well-suited to this? I sort of get the impression that Ember.js and Angular.js are too heavy duty for this sort of thing. Would Backbone.js work potentially? Also, is there any reason why I shouldn't just roll my own (using AJAX requests with Mustache.js templating)?




How to reference ember.js controllers that are in nested folders?

I'm building an EventController that has little modules of logic within sections or div's of the event screen.

Say for instance, event details may be in the main Event template but a small section might be the user's status with the event such as whether they RSVP'd etc. but since it's controlled by a different model than the event I'd think it should have it's own controller.

Would I put this in the EventController like such:

Controller = BaseController.extend
  needs: ['event/user-status-area']
  userStatusArea: Ember.computed.alias("controllers.event.user-status-area")

This obviously isn't working otherwise I wouldn't be here... but I'm looking for suggestions.

I'm very new to ember / ember-cli concepts so I'm sorry if I'm just blatantly way off base here.

In my brain, I would imagine keeping everything about an event centralized under the one EventController...

Am I missing something big? Is this possibly where the "Router" comes in?




Creating a new model in ember with a zurb foundation range slider bound to an attribute

I am trying to use the range slider from the zurb foundation framework with Ember. I want a slider next to an input field, both of them showing the same value updating each other so a user would be able to enter either a number by hand or use the slider to set a score for a game played in the past.

My template looks like this:

{{input type="text" id="new-game-score" value=newGameScore}}
<div class="range-slider" data-slider={{newGameScore}} data-options="start: 0; end: 16;">
  <span class="range-slider-handle" tabindex="0" role="slider"></span>
  <span class="range-slider-active-segment"></span>
</div>

And in the controller I'm calling this.get('newGameScore'); to get the value for the creation of the model.

When I open the template I get a text-input that behaves like I expect. It allows to set the score for the creation of the model. The data-slider-attribute of the slider next to it gets updated correctly, but it doesn't change how the slider looks and I can't move the slider at all. When I set newGameScore as a function returning a number in the controller both the slider and the input field start out with the set value and I can move the slider. Moving it does not change the value of the input field though, while entering a number in the text field adjusts the data-slider-value without any visible change on the slider. The number used for the creation of the new model is the one from the text input.

I'm using ember-cli and installed foundation with ember install ember-cli-foundation-sass. I have

var app = new EmberApp({
  'ember-cli-foundation-sass': {
    'modernizr': true,
    'fastclick': true,
    'foundationJs': 'all'
  }
});

in my Brocfile and the corresponding view looks like this:

export default Ember.View.extend({
  didInsertElement: function() {
    this.$().foundation();
  }
});

The controller is an ArrayController with the template showing all the games with their scores. I would like to keep at that way if possible.

I started out using the zurb foundation documentation: http://ift.tt/1pLQ9tO

and found the following solution to a more complicated but closely related problem: http://ift.tt/1dwuK6V

but I couldn't figure out how to properly synchronise the slider with newGameScore. http://ift.tt/1dwuK6V states at the beginning of the article that ember with a foundation-slider is easy to do. So I assume I don't have to write custom on-change-functions to solve my problem, but maybe someone more experienced with ember can find a solution from bottom part of the article, although it seemed to me that this is only needed for the combination of the dropdown and the slider.

Thanks for reading and for any idea about this. regards, Andy




jQuery Plugin into Ember component

I am trying to turn this jQuery plugin http://ift.tt/VItLX2 into an Ember component.

import Ember from 'ember';

export default Ember.Component.extend({

tagName : "input",
type : "text",
attributeBindings : [ "name", "type", "value", "id"],

_initialize: function() {

    Ember.assert("Tags Input has to exist on Ember.$.fn.tagsInput", typeof Ember.$.fn.tagsInput === "function");

    this.$('#tags').tagsInput({'width':'100px'});

}.on('didInsertElement')
});

Then in my handlebar file {{tag-input id="tags"}}

But it seems that the jQuery isn't working as it is just a standard input box. This is the generated HTML <input id="tags" class="ember-view" type="text"></input>

But if I copy this.$('#tags').tagsInput({'width':'100px'}); into the console and run it the element uses the plugin.

What would be the reason that the plugin wouldn't get fired on didInsertElement?




Suggestion where to encapsulate/abstract/refactor third party library?

I am using filepicker to manage uploads. I have a few components/controllers doing the following:

  1. Creating a filepicker variable
  2. Setting a key via filepicker.setKey(config.FILEPICKER_API_KEY)
  3. Using one of its methods like pickAndStore

The code logic:

var filepicker = window.filepicker;

// Store an image file
filepicker.setKey("AZF9nmEYQJmx41xvJomGQz");
filepicker.pickAndStore(
  // http://ift.tt/1EFdQwQ
  // Example:
  {
    mimetype:"image/*",
    folders:true
  },
  {
    location:"S3"
  },
  function(Blobs){
    console.log(JSON.stringify(Blobs));
  }
);

// Convert an image
filepicker.setKey("AZF9nmEYQJmx41xvJomGQz");
filepicker.convert(
  // http://ift.tt/1EFdOFq
  // Example:
  {
    url: 'http://ift.tt/1AkdVAS',
    filename: 'customers.jpg',
    mimetype: 'image/jpeg',
    isWriteable: false,
    size: 629454
  },
  {
    width: 200,
    height: 200
  },
  function(new_Blob){
    console.log(new_Blob.url);
  }
);

I was thinking of refactoring this out somewhere to avoid repetitiion and better logical encapsulation.

So the first thing I did was set the key as an ENV variable at config/environment.js, and replaced filepicker.setKey("AZF9nmEYQJmx41xvJomGQz") with filepicker.setKey(config.FILEPICKER_API_KEY).

The next thing I was thinking of doing is figuring out where to declare the filepicker variable and store some of the more common methods (i.e. pickAndStore and convert).

At first glance I thought of creating a service and initializer. The service could look like (pseudo code):

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

var filepicker = window.filepicker;

export default Ember.Service.extend({
  init: function() {
    filepicker.setKey(config.FILEPICKER_API_KEY);
  },

  pickAndStore: function(args*) {
    // ...
  },

  convert: function(args*) {
    // ...
  },
});

Is there a general best practice/pattern for code like this to go somewhere? The solution/approach you end up suggesting can also be applied to other third party libraries that have a similar type of integration.




setting model from route upon action received in ember.js

I am trying to set a model value from an action received by my route.

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

export default Ember.Route.extend({
  model: function() {
    return {
      trail: null
    };
  },
  actions: {
    event: function(name, value) {
      if (name === 'trail.selected') {
        this.modelFor('map').set('trail', value);
      }
    }
  }
});

when I try to use

 this.modelFor('map').set('trail', value);

I get the following error:

Uncaught TypeError: this.modelFor(...).set is not a function

When I try to use

this.modelFor('map').trail = value;

I get that error

Uncaught Error: Assertion Failed: You must use Ember.set() to set the trail property (of [object Object]) to <nested-component@model:mtg-trail::ember617:kvdpo>.




Getting a hash of all values inside form in Ember

I am submitting a form to create a new Review in Ember.js. The form is linked to an action on my reviews/new controller.

Here is my form:
templates/reviews/new.hbs

  <form {{action "createReview" on="submit"}}>
    {{input value=name}}
    {{input value=content}}

    <input type="submit" value="Post this review" class="button">
  </form>


And my controller:
controllers/reviews/new/js

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    createReview: function(params) {
      console.log(this.get('name'));
      console.log(this.get('content');
    }
  }
});

At the moment my trouble is accessing the form field values in an efficent way. Note that this.get('name') does print out the value of the name input field and the same for this.get('content').

But is there a nice way to get all the form field values in a hash? Something like: this.get('allAttributes') which would output:

{name: "John Doe", content: "Bla bla-bla bla blaaaaah"}




How can I display a specific view in the main application template with EmberJS

Begginer with EmberJS, I am wondering how can I display a specific view in my main template ? enter image description here

When I click on the menu in application.hbs I want to display User,Event What is the best practice, using component ? moddal views ? Do you have any good tutorial ?




emberjs ember-cli - how to remove deprecated notice for {{#each}}

This is using ember-cli 0.2.3

(model) todo.js

import DS from 'ember-data';

export default DS.Model.extend({
   title: DS.attr('string'),
   isCompleted: DS.attr('boolean')  
}).reopenClass({
   FIXTURES: [
      {
        id: 1,
        title: "Complete Ember.js Tutorial",
        isCompleted: false
      },
      {
        id: 2,
        title: "Checkout some more ember stuff",
        isCompleted: true
      },
      {
        id: 3,
        title: "Solve world hunger (with Ember)",
        isCompleted: false
      }
   ]
});

in router.js

this.resource('todos', { path: '/' });

in todos.js

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

in todos.hbs

{{#each}}
    //some code here using the model
{{/each}}

in developer console got this notice:

DEPRECATION: Using the context switching form of {{each}} is deprecated. 
Please use the keyword form (`{{#each foo in bar}}`) instead

Please advice on the actual each code for removing the deprecation notice.

The following are codes that I tried:

1 - {{#each todo in todo}} //no error, but no data in todo list
2 - {{#each todo in controller.todo}} //no error, but no data in todo list
3 - {{#each todo in todos.todo}} //no error, but no data in todo list
4 - {{#each todo in todos}} //no error, but no data in todo list

THANK YOU - for any help, cheers!




confused between loading json on routes or on models

Good day ,

Im new at emberjs and im starting to learn how it works,

what is the difference when specifying the json on routes or on models

model: function() {
var url = 'http://ift.tt/1b39EeD';
return Ember.$.getJSON(url).then(function(data) {
  return data.splice(0, 4);
});

},

this is how i call the json on routes , now my problem , what is the used of this function

export default DS.RESTAdapter.extend({});




What exactly does Ember.MODEL_FACTORY_INJECTIONS do?

I'm using Ember CLI and by default it seems to set Ember.MODEL_FACTORY_INJECTIONS = true; in app.js.

I tried commenting this line out (and setting it to false) and then my app seemed to behave in some sort of strict mode. I got a bunch of failed assertions because some of my Model relations didn't explicitly specify the inverse.

This is the exact error:

You defined the 'account' relationship on (subclass of DS.Model), but multiple possible inverse relationships of type (subclass of DS.Model) were found on (subclass of DS.Model). Look at http://ift.tt/1aomJhS for how to explicitly specify inverses

Using the default Ember CLI generated app with Ember.MODEL_FACTORY_INJECTIONS = true;, I didn't get these errors. So I'm lead to believe that this flag changes core behaviour somehow.

Insight please!




One way binding from DOM element to Controller property - Ember

In my ember application I've a file input DOM element. I bind the value attribute of the element to a controller property.

I do this to know when the file input's value changes. But I don't want to set the value from the controller. I mean one way binding. DOM element to controller and not controller to DOM element.

Handlebar code :

{{input type="file" name="pic" accept="image/*;capture=camera" id="newImage" value= imagePath}}

Controller :

App.ExampleController = Ember.ObjectController.extend({
    imagePath: null,
    imageChanged: function () {
        //Some Code
    }.observes('imagePath')
});

I need this because I get the following error

Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. thrown by jquery-1.11.1.min.js

Is there a way to fix this ?




mercredi 29 avril 2015

How to render a templates by its controllers name in ember.js

I have multiple controller and its view lets say for example controller name is fire and its view name is fire like wise I have multiple controller and its views. I am able to get all the controller name using using following way.

var x = app.get('sections');
 var controller;
 for(var j = 0; j < x.length; j++)
 {
         console.log(x[j].id)
         controller = app.controllerFor(x[j].id);
         alert(controller);
  }

Here I am getting all the controller names as per name is get from all sections.

As per different sections I have created templates as per the sections name. Now I have to store all the template contain for all the sections in a separate array.

Thanks




How to break-down the drop-down labels using ember.js

Here i am using Ember.select class for display the Drop-downs in my application, i need to break-down long labels into newline for every 25 characters, see my below .hbs code, "optionLabelPath="content.name" is the label it is retreiving from array of object

{{view Ember.Select contentBinding=entities optionLabelPath="content.name" optionValuePath="content.id" prompt="-- Select --" valueBinding=entityId}}

and i used css for option but it does't work

my css code

option {
    width: 11em; 
    border: 1px solid #000000;
    word-wrap: break-word;
}




What's wrong to mix jQuery with http://ift.tt/1DLGgkX?

I came from backend dev to frontend dev just recently, so I'm a totally newbie here and having a lot troubles cleaning my head up.

One of the problems is that I was trying to integrate twitter-bootstrap-3 with one of the mvvm frameworks naming backbone.js, angular.js and ember.js. I was really confused to see some repos in GH trying to rewrite some js part of bootstrap. What's wrong with jQuery in these frameworks? Would it be wrong to mix jQuery code into these frameworks? Thanks a lot!




Which version should I choose when I want to use Ember.js?

I am currently considering using ember.js as my mvc solution.

I have learnt Version 1.10. It is merely a js mvc framework. But now Version 1.11 has released with huge modification. It is now more like a web container.

With Version 1.10, one can use it with Express(node.js) or JavaEE container. These back-end solutions are mature and familiar to me.

However, with Version 1.11, I think it is more like a standalone application. No additional back-end is needed.(Actually, It looks like one has to implement the backend logic inside the ember app.)

I currently haven't used Emberjs in any production yet. I am aware of that things can be more complicated when switch from study project to productional project.

So I wish people with emberjs production experience can give some advises. I have following enquiries.

  1. Is Version 1.10 + Express(or Java EE) a good combination for production? Is 1.10 a reliable version? Is it adequate? What is the most difficult part while adopting to this methodology?
  2. Is Version 1.11 a reliable platform, in perspective of a web container? Compared with the methodology above(1.10+Express or Java EE), what are the strengths and drawbacks of Version 1.11?
  3. Other tips or considerations of using Emberjs are appreciated as well!



Ember simple-auth-token won't whitelist API server

I've been pulling my hair out trying to figure out what I've missed; I'm using the simple-auth and simple-auth-token libraries (via ember-cli 0.2.3) and can't seem to get my app to set the appropriate Athentication: HTTP header. From what I've read, the most common oversight is people not setting the crossOriginWhitelist: property on the simple-auth ENV variable. However, even with a value of ['*'], I can't seem to get Ember to send the headers with my API requests. Mind you, I'm replacing a previous hand-rolled (though, half-baked!) auth solution, so I know my API server works and will authenticate, given the right credentials.

When I run the login action everything works flawlessly. If I hit a protected Ember route after that, it works fine as well. The problem comes when Ember-data tries to hit my API (at http://localhost:3000); it gets back a 401 (since it didn't set the Authorization: header) and transitions to the index of my site.

Here's the relevant sections of code:

config/environments.js

...

ENV['simple-auth'] = {
    authenticationRoute: 'login',
    authorizer: 'simple-auth-authorizer:token',
    crossOriginWhitelist: ['*']
};
ENV['simple-auth-token'] = {
    identificationField: 'email',
    passwordField: 'password',
    tokenPropertyName: 'token',
    authorizationPrefix: 'Bearer ',
    authorizationHeaderName: 'Authorization'
};
...

routes/login.js

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    login: function(){
      var creds = this.controller.getProperties('identification', 'password');
      this.get('session').authenticate('simple-auth-authenticator:jwt', creds)
        .then(function() {
          // +
          }, function() {
          // -
      });
    }
  }
});

routes/application.js

import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin);

Thanks in advance.




How to highlight a autocomplete list using the the Up key and the Down key (Ember.js)

I have a auto complete and i will like to go thru the list using the up and down key to be able to highlighted here it is a example that how I want to be able to work http://ift.tt/1DWZ6on. I created a auto complete jsbin for the purpose http://ift.tt/1P845Jg

App.AutocompleteController = Ember.Controller.extend({
  searchText: null,
     searchResults: function() {
        var searchText = this.get('searchText');
        if (!searchText) { return; }

        var regex = new RegExp(searchText, 'i');
        return ['one', 'two', 'three'].filter(function(name) {
          return name.match(regex);
        });
      }.property('searchText')
    });




move Up and Down with key thru a list of item (Ember.js)

what I, am trying to do is move up and down thru a list of item using my keyboard. Here is a perfect example of how to do it on jquery http://ift.tt/1DWZ6on . I want to be able to accomplish this only using ember.js

   keyDown: function (e) {
         var moveDown = 40;
         var moveUp = 38;

         if(e.keyCode === moveDown || e.keyCode === moveUp){

         }
     }




How do I get the current folder in NodeJS for a Browserify'd file that relies on a base file in another folder?

I'm using AmpersandJS and I'm trying to emulate the pod structure of Ember so that, instead of the typical folders-per-type structure:

app
|-- views
    |-- index.js
    |-- login.js
    |-- people.js
|-- templates
    |-- index.jade
    |-- login.jade
    |-- people.jade

you have folders-per-component instead:

app
|-- index
    |-- view.js
    |-- template.jade
|-- login
    |-- view.js
    |-- template.jade
|-- people
    |-- view.js
    |-- template.jade
|-- base-view.js

I'm using templatizer to compile my templates:

templatizer(__dirname + '/app', __dirname + '/app/templates.js');

Which will make the template object look something like this (simplified for sake of explanation):

{
    "index.template": "<div>index</div>",
    "login.template": "<div>login</div>",
    "people.template": "<div>people</div>"
}

In the base view, I have the following, which will return the template by convention:

var BaseView = AmpersandView.extend({
  template: function() {
    // pretend that I'm cleaning up __dirname here
    return templates[__dirname].template;
  }
});

and in my other views, I'm extending the base view:

// in app/index/view.js:
var IndexView = BaseView.extend({ ... });

The problem I'm running into is that, when the base view goes through Browserify, __dirname is set to the folder of the base view template, and not the view that's extending it. As a result, __dirname will always be /app, even though /app/index/view.js is the view that's being rendered.

I was wondering if it's possible to get the dirname of the current view rather than the base view. I know that I can add something like templatePath to each view that the base view will read, but I'm trying to avoid having to do that.




how to get reference of Rickshaw with Ember-cli using ember-rickshaw

In my ember js app, created using ember-cli, I want to create a real time graph to be displayed. I thought of using ember-rickshaw.

I followed the example found here, and then tried to run a simple code. The problem is it gives me this error uncaught reference: Rickshaw is not defined. I have installed rickshaw, ember-rickshaw and d3 all using npm. and hence they reside in the node_modules folder. After this error, I tried to include their corresponding files in the brocfile.js, this way:

app.import('node_modules/ember-rickshaw/dist/ember-rickshaw.min.js');
app.import('node_modules/rickshaw/rickshaw.js');
app.import('node_modules/d3/d3.min.js');

but then it says it can not find the files, though the files are at exactly these locations.

May be I'm missing how to import any javascript library into ember cli.

Following this SO link, I tried to use

<script src="../../node_modules/ember-rickshaw/dist/ember-rickshaw.min.js"/>
<script src="node_modules/rickshaw/rickshaw.js"/>
<script src="node_modules/d3/d3.min.js"/>

in the template file /my_graph.hbs. But it again gives the same error to not have defined the Rickshaw reference.

Any help is greatly appreciated. Thanks.




How do you update the rails index controller to accept ids parameters when using Ember Data coalescing?

If you are using Rails API and Ember JS and enable coalescing in Ember Data (example), Ember Data will coalesce your queries into one that will automatically hit your index controller with an ids parameter of what it wants.

How do you update the index controller? Is there a ActiveRecord function for retrieving all or some records based on a parameter being included?

def index
  ids = params[:ids]
  if ids.present?
    @advertisers = Advertiser.where(id: ids)
  else
    @advertisers = Advertiser.all
  end

  render json: @advertisers
end




How can I insert bootstrap-autohindingnavbar into ember application?

I'm new to ember, and I've been searching a lot for doing that navbar-fixed-top hides when scrolling in an ember app. The code is:

$(".navbar-fixed-top").autoHidingNavbar()

that's all. It seems easy... but when it comes to where put it and how deal with this simple expression, I found no clear answer.




Serialize records without id in embedded record mixin

I started looking on embedded record mixin for serialising/deserialising records with hasMany/belongs to relationship.

Model:

 App.Post= DS.Model.extend({

   comment: DS.belongsTo('comment'),
   name:     DS.attr('string')
 });

 App.Comment =DS.Model.extend({

  post: DS.belongsTo('Post'),
  value:   DS.attr('string')
 });

Serializer:

App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
   attrs: {
      comments: {embedded: 'always'}
   }
});

When i try to save the model,i got the following error.

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

    model.get('comments').pushObject(this.store.createRecord('comment'));


    model.setProperties({
        name: 'test'
    });

    model.save();

Error: Assertion Failed: You must include an id for App.Comment in an object passed to push . Only the error in browser console but to the backend ,data goes as expected.

So, i started looking for workaround and found something interesting in http://ift.tt/1DKPMVw.

source : http://ift.tt/1HRLv7N

On following that link, i changed my serialiser as follows.

Serializer (changed):

  App.PostSerializer=DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin,DS.NoKeyMixin, {
        attrs: {
          comments: {embedded: 'always',noKey: true}
        }
     });

But when i save the model now, i am getting the floowing error.

Uncaught TypeError: embeddedRecord.serialize is not a function.

I am stuck on this and looking for help. Thanks in advance.




Ember library causing "Binding Style Attributes" deprecation warning

I'm trying to use the ember-cli-file-picker to load a file into my app for processing in the browser. It works but raises the following deprecation error

WARNING: Binding style attributes may introduce cross-site scripting vulnerabilities; please ensure that values being bound are properly escaped. For more information, including how to disable this warning, see http://ift.tt/1PYJXLZ attributes.

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

I'm thinking that this is because of

progressStyle: computed('progressValue', function() {
  var width = this.get('progressValue') || 0;

  return htmlSafe('width: ' + width + '%;');
})

in the library. I'm pretty new at ember, and am not positive that the library is safe, nor how to silence the deprecation warning using SafeString if it is. What should I do?




How can I wrap jQuery Justified Gallery in an Ember Component?

I'm trying to wrap the plugin Justified Gallery in an Ember component. The main problem that I'm facing is that the list of photos in the gallery come from an API, so they're part of the model. What I have so far:

App.JustifiedGalleryComponent = Ember.Component.extend({
    _init: function() {
        this.$().justifiedGallery({
            rowHeight: 150,
            fixedHeight: false,
            margins: 7
        });
    }.on('didInsertElement')
});

Template

{{#each photo in items}}
  <div>
    <img src={{photo.thumbUrl}} />
  </div>
{{/each}}

But I can't get that to work, probably because the list of photo is inside an each loop, and when the plugin is applied the photos are still not in the DOM? What would be the approach for this problem?

Thanks!




How to enable CORS in an EmberJS application?

I have an EmberJS application that uses ember-data to access data via a REST API. The REST API is running on the same machine but on a different port (although this probably applies to REST API's that are served from another domain.

When I go to the URL localhost:4200/items I get the following error in the Firefox console:

Content Security Policy: The page's settings blocked the loading of a resource at http://localhost:7654/api/items ("connect-src http://localhost:4200 ws://localhost:35729 ws://0.0.0.0:35729 http://0.0.0.0:4200").

I tried installing ember-cli-cors but nothing changed. I also tried the solution at http://ift.tt/1DWboNK, but that didn't work either. That discussion was from 2013, so that's not a huge surprise.

The REST API is written in python using Flask and Flask-cors. Using the network tab I can see that the request is being sent, and the data being sent back, but the error is still there.

app/router.js

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

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

export default Router.map(function() {
  this.route('items');
});

app/adapters/application.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  namespace: 'api',
  host: 'http://localhost:7654',
});

app/routes/items.js

import Ember from 'ember';

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

app/models/item.js

import DS from 'ember-data';

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

app/templates/items.hbs

{{#each item in items}}
  {{ item.name }}<br>
{{else}}
  <p>No items</p>
{{/each}}

{{outlet}}




Modularization of large Ember application

We are considering to use EmberJS for a large project. We are in early stage of proof-of-concepts, but we like the core concepts of Ember so far. However, we are little bit lost regarding how to structure and modularize our project.

We have started with ember-cli (based on broccoli) that provides simple project structure and basically compiles all assets into few files that are all served right away to the client. We would like to do two things:

1. Split project into two layers:

  • Company-wide foundation of UI components, that can be reused in our other projects. This layer may basically contain anything that we consider reusable and not product specific. Components, templates, utility helpers, mixins, reusable views and controllers, perhaps user management and other common stuff.

  • Product application layer built on top of previous layer. This will contain actual screens, routes, application logic and product-specific components and views.

It would be very helpful if the two layers could be in two separate repositories, but still could be easily developed and managed at once. I like a concept of git submodules for dealing with multiple repositories in one project during a development. It would be great if we could build, test and pack the first layer separately and once built, use it as a dependency for the final product built on top of it.

2. Build separate packages and load them dynamically by client

We would like to avoid building whole application into one big app.js file and load it on client every time. Instead we would like to split application during build into several smaller packages that are loaded on client by demand.

There are several reasons for this:

  • We have different kinds of users that work with the application based on their role and permissions. While some users may only use few screens, others may use much more screens or a different set of screens based on their permissions. For example there's no need to load administration part of the application if the client has permission only to access basic functionality of the application. This is mainly for optimization but also for security. I think we can draw lines between modules mostly on URL / routes.

  • We will offer different licenses for the product. We don't want to ship parts of application that the customer has not a license for. Again I think we can split modules by URL / routes in this case.

  • We would be very happy if we could build a small package that contains all necessary components to let user launch the application and log in, then load the rest of the application once the user logs in.

To summarize, there are two things that we need to solve:

  1. Split an application into multiple packages during a build
  2. Dynamically load demanded packages on a client

I have no idea how to adapt build process (currently ember-cli and broccoli) to our needs. I can imagine how to deal with dynamic loading on a client though. I think we could use promises in route's "model" hook to asynchronously load required module that contains all required resources and inject them into Ember DI container. I'm not sure if Ember contains any logic (other than route's model hook) that would support such a dynamic loading. To my current knowledge, Ember just throws exception if it cannot find requested resource (like controller, view, template etc.) in its container. That would mean that we have to make sure that the package that we load for the route contains everything that can be possibly needed inside the route and manually inject it into the container. I'm fine with that approach if we have tool that tells us all dependencies for any given route, which I guess isn't easy. That dependency tree would have to be used in the build process as well.

Guys, any ideas? :)

ORIGINAL QUESTION ON EMBER DISCUSS FORUM




Ember.js install on Windows: Will not load app: Cannot find module 'ember-cli/lib/broccoli/ember-app'

Just installed ember.js on Windows machine (XP) - new to ember.js setting up dev machine.

Necessary components seem to be present and responsive.

$ember version gives me:

version: 0.2.3
node: 0.12.2
npm: 2.7.6

$npm version gives me:

{ alquimista: '0.0.0',
  npm: '2.7.4',
  http_parser: '2.3',
  modules: '14',
  node: '0.12.2',
  openssl: '1.0.1m',
  uv: '1.4.2-node1',
  v8: '3.28.73',
  zlib: '1.2.8' }

When I switch to my ember app directory and run

$ember server

I get an error

version: 0.2.3
Cannot find module 'ember-cli/lib/broccoli/ember-app'
Error: Cannot find module 'ember-cli/lib/broccoli/ember-app'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (Y:\webwork\emberjs\alquimista\Brocfile.js:3:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)

Yes, I have confirmed "ember-cli/lib/broccoli/ember-app" exists and is in the PATH variable in a fully qualified form, c:/.. etc . But the error msg does not contain the fully qualified path so I wonder if ember.js is using a relative path on load? I don't know what base directory it would be starting from and referencing based on.

Does anyone have a suggested fix to get the ember server running on a Windows machine in a case like this?




How dinamically load route in EmberJS?

Need on change search field - load route with params /search/WORD, path of route, example, /search/:q

How is best way?

  1. In template {{input value=str}} and in controller this.transitionToRoute('search', this.store.find...) . It require loading model in controller and duplicate to route mode:function(){ return this.store.find...}.
  2. In controller call route by url this.transitionToRoute('/search/' + str).

Else?




emberjs menu component bubbling

I have a menu component, which build a tree menu from an array. To toggle the sub menus I do:

  didInsertElement:function(){
    this.$('li.sub').click(function(e){
      $('ul', this).slideToggle();
    });
  }

I works fine as long as I click on 'Settings'. If I try to click one of the sub menus ex. 'Currency' It closes the parent menu item.

Here is a jsBin to demonstrate the problem: Click on 'Settings' -> then click one of the opened sub items:

http://ift.tt/1znG0fZ




EmbeddedRecordsMixin not working as expected, what am I missing?

I'm trying to use embedded records in ember data and I think I'm missing something fundamental.

I have two models

app/models/video.js:

export default DS.Model.extend({
  title: DS.attr('string'),
  transcriptions: DS.hasMany('transcription', { embedded: 'always' })
});

app/models/transcription.js:

export default DS.Model.extend({
  video: DS.belongsTo('video')
});

I also have a custom serializer app/serializers/video.js:

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs:{
    transcriptions: { embedded: 'always' }
  },  
  extractSingle: function (store, type, payload, id) {
    var data = payload.data;
    return {
      id: data._id,
      title: data.Title,
      transcriptions: [{ id: "1" }] 
  };
},

I would expect that this would result in my video model being populated with transcriptions being an array of transcription object but instead I get the following error:

"Error while processing route: videos.show" "Assertion Failed: Ember Data expected a number or string to represent the record(s) in the transcriptions relationship instead it found an object. If this is a polymorphic relationship please specify a type key. If this is an embedded relationship please include the DS.EmbeddedRecordsMixin and specify the transcriptions property in your serializer's attrs object."

Any suggestions of what I'm doing wrong here would be greatly appreciated.




Handle Softdeletable Entities in Ember Store

We had to add a deleted flag to the entities we used in our application.

For example, our Answer entity looks like this:

App.Answer = DS.Model.extend({
    text: attr('string'),
    score: attr('number'),
    question: belongsTo('question', {inverse: 'answers'}),
    deleted: attr('boolean', {defaultValue: false})
});

A Question entity looks like this:

App.Question = DS.Model.extend({
    text: attr('string'),
    nextQuestions: hasMany('question'),
    answers: hasMany('answer', {inverse: 'question'}),
    deleted: attr('boolean', {defaultValue: false})
});

The same changes apply to all our 15+ entities. Note: we load all the data from server at once and use ember localstorage adapter.

The problem: The application can be 'virtually' splitted into 2 module: admin section (where I must display the deleted entities too) and the rest of the application, used by normal users who must not see the deleted entities.

One solution: So, in some screens I could use the getter directly, like: questions.get('answers'), in others I would have to filter the answers and skip the ones which are deleted. The easiest way would be to use an Ember.computed helper.

App.Question = DS.Model.extend({
        text: attr('string'),
        nextQuestions: hasMany('question'),
        answers: hasMany('answer', {inverse: 'question'}),

        activeAnswers: Ember.computed.filterBy('answers', 'deleted', false)

        deleted: attr('boolean', {defaultValue: false})
    });

Still, this means that we have to re-factor all our entities and all our controllers, which is a major change and will take a lot of effort.

Others solutions I'm thinking on emulating 2 ember stores if that's possible and use them separately, one for the admin screens which would contain the deleted entities and the other one for the rest of the application.

Does anyone see a better approach for this change? Something which could work at ember's store level and would not affect the models and controllers?

Thanks! Any advice is greatly appreciated.




Cannot read property 'match' of undefined at Ember.DefaultResolver.extend.podBasedComponentsInSubdir

I'm getting a really opaque error message (opaque in the sense I have no point of reference for my own source) from console, I'm not entirely sure where to look, I feel it's likely an error in library code but before posting this on github I'll just double check it's not my own fault.

The Problem

The Problem is simple, I'm calling this.store.find('player'), in hopes to get a list of all players, and then display them in some kind of list, but I'm not even getting past the loading part. The data is pulled from the server and looks properly formatted, but something seems to be failing after the route.model method call. And the error message seems to be somewhere in the ember.js library code with nothing pointing back to my own code.

Server Response

The content type is of course application/json, and note the id property is actually _id.

[
  {
    "_id":"55405a5102b4ed623c225e87",
    "alias":"mikeTest",
    "__v":0,
    "scans":[],
    "createdAt":"2015-04-29T04:13:05.223Z"
  }
]

Error message

Note there is part of the stack trace pointing to my source, only Ember source. Which has made this a pain to debug.

Error while processing route: leader Cannot read property 'match' of undefined TypeError: Cannot read property 'match' of undefined
    at Ember.DefaultResolver.extend.podBasedComponentsInSubdir (http://localhost:4200/assets/vendor.js:60138:76)
    at http://localhost:4200/assets/vendor.js:60190:34
    at Array.exports.default.mixin.Mixin.create.find (http://localhost:4200/assets/vendor.js:39572:30)
    at Ember.DefaultResolver.extend.findModuleName (http://localhost:4200/assets/vendor.js:60188:44)
    at resolveOther (http://localhost:4200/assets/vendor.js:60051:37)
    at superWrapper (http://localhost:4200/assets/vendor.js:28141:20)
    at exports.default.EmberObject.default.extend.resolve (http://localhost:4200/assets/vendor.js:15454:35)
    at Object.resolve [as resolver] (http://localhost:4200/assets/vendor.js:15217:23)
    at resolve (http://localhost:4200/assets/vendor.js:12792:29)
    at Object.Registry.resolve (http://localhost:4200/assets/vendor.js:12336:21)

Source

This ember app is very young, so there is very little source at the moment, but this is all the relevant source at the moment.

Routes

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

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

export default Router.map(function() {
  this.resource('leader');
  this.resource('profile');
  this.route('loading');
});

Leader route

Leader has a template and a controller, but they are basically empty right now.

import Ember from 'ember';

export default Ember.Route.extend({
  model: function () {
    return Ember.RSVP.hash({
      players: this.get('store').find('player')
    });
  },
});

Player Model

import DS from 'ember-data';

export default DS.Model.extend({
  alias: DS.attr('string'),
  createdAt: DS.attr('date'),
  scans: DS.hasMany('scan'),
});

Application Adapter

import DS from 'ember-data';


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

Application Serialiser

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  primaryKey: function (type) {
    return '_id';
  },

  serializeId: function(id) {
    return id.toString();
  }
});

Package.json

{
  "name": "hunter",
  "version": "0.0.0",
  "description": "Small description for hunter goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "start": "ember server",
    "build": "ember build",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.0.2",
    "ember-cli": "0.2.3",
    "ember-cli-app-version": "0.3.3",
    "ember-cli-babel": "^5.0.0",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "0.0.8",
    "ember-cli-htmlbars": "0.7.4",
    "ember-cli-ic-ajax": "0.1.1",
    "ember-cli-inject-live-reload": "^1.3.0",
    "ember-cli-jshint": "0.0.0",
    "ember-cli-qunit": "0.3.10",
    "ember-cli-sass": "4.0.0-beta.6",
    "ember-cli-uglify": "1.0.1",
    "ember-data": "1.0.0-beta.16.1",
    "ember-export-application-global": "^1.0.2",
    "semantic-ui-ember": "0.0.1-rc.8"
  }
}

Things I've tried

  • removing properties from the model, in the event the relationships seemed to be the problem (nothing changed)
  • tried setting up a serialiser and adapter for the application (included above), nothing changed.
    • the serialiser in the event that the id field in the response is actually _id.
  • tried updating ember data, nothing changed.



mardi 28 avril 2015

How do enable the format.js helpers in Ember Unit tests

I am using Ember with formatjs to internationalize my application, and ember-cli to build it all.

When I generate a component with

ember g component some-component

Ember also creates a test that checks that the component renders. However, if I use the intl-get helper from formatjs in the component template, the unit test fails.

So how can I register the custom helpers that formatjs creates for a unit test?

I first tried to add the intl-get helper:

moduleForComponent('some-component', {
  needs: ['helper:intl-get']
});

However, this just fails inside intl-get when it tries to access "intl:main". I would like for the intl initializer to run, but I am not sure if there is even application setup. Or is it some way to just mock those methods using sinon?

My current workaround is to just delete the 'it renders' tests. But I would like for these tests to pass as well, so I can further test rendering later if I want.




Unit testing Ember utils. TypeError: factory.create is not a function

I've created util here: app/utils/filters-serialization.js

export default function filtersToString(search) {
  return 'keyword$MO';
};

And test here: tests/unit/utils/filters-serialization-test.js

import {
  moduleFor,
  test
  } from 'ember-qunit';

moduleFor('util:filters-serialization', {
});

test('it exists', function(assert) {
  var service = this.subject();
  assert.ok(1);
});

I run tests and I've got an error TypeError: factory.create is not a function The problem occurs when I call this.subject();. If I remove this line everything works well. But I It will be great if someone could share his experience in writing unit tests for ember utils. I found another question: Unit testing modules in app/utils for an ember-cli app however this.subject isn't undefined anymore so I think it's good to ask this question again




ember-data: find return nothing in local storage adapter

Ember : 1.11.1

Ember Data : 1.0.0-beta.16.1

jQuery : 1.11.2

"ember-localstorage-adapter": "0.5.3"

I have an issue regarding storage in ember.js

I am able to save records in the storage adapter, but not retrieve them...

create record:

this.store.createRecord('mtgTrail', {name: "foo"}).save()
Class {__ember1430287079605: null, __nextSuper: undefined, __ember_meta__: Object, constructor: function, _super: function…}

find with all:

this.store.all('mtgTrail').forEach(function(trail) { console.log(trail.get('name'))})
foo
Class {type: function, content: (...), store: Class, isLoaded: true, manager: Class…}

find with find:

this.store.find('mtgTrail').then(function(trails) { trails.forEach(function(trail) { console.log(trail.get('name'))})})
Promise {_id: 188, _label: undefined, _state: undefined, _result: undefined, _subscribers: Array[0]…}

content of localstorage:

localStorage.getItem('mantrailling')
"{"mtgTrail":{"records":{"liet8":{"id":"liet8","name":"test","address":null,"features":null,"selected":true,"createdAt":"Wed Apr 29 2015 07:57:50 GMT+0200 (Paris, Madrid (heure d’été))","level":null,"items":[]},"3kskq":{"id":"3kskq","name":"foo","address":null,"features":null,"selected":false,"createdAt":"Wed Apr 29 2015 07:57:50 GMT+0200 (Paris, Madrid (heure d’été))","level":null,"items":[]}}}"

As you can see, localStorage has 2 mtgTrail, I am able to retrieve on with all, but none with the find function




Child route not rendering on Ember

I am obviously messing up something here, but I have a child route called 'details' that I want to render. However I keep getting error messages that 'details' does not exist.

Here's my router map:

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

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

export default Router.map(function() {
  this.resource('lists', {path: '/'}, function() {
    this.route('show', {path: 'lists/:list_id'} );
  });
  this.route('todo', {path: 'todos/:todo_id'}, function() {
    this.route('details');
  } );
});

The link to details route:

<div class="row">
    {{!div class="col-xs-12 col-xs-offset-5"}}
    {{!task list}}
        <ul class="list-group">
            {{#each todo in model.todos itemController="todo"}}

                {{#link-to "todo.details" todo}}

                <li class="list-group-item">
....

todo/details.hbs:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <div class="container-fluid">

        <div class="row">
            <h3>{{todo.model.title}}</h3>


        </div>

        <div class="row">
            <li>
                <p>my name<small>timestamp</small></p>
                <p class="bubble">yea</p>
            </li>
        </div>

        {{outlet "comments"}}

    </div>

todo/details.js:

export default Ember.Route.extend({
    renderTemplate: function() {
        this.render('comments', {
            into: 'details',
            outlet: 'comments'
        });
    }
});

todo.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params){
    // return model
  },
  renderTemplate: function(controller) {
    this.render('lists.show', {controller: controller});
//    this.render('todos', {controller: 'todo'});

    this.render('todos', {
        into: 'lists.show',
        outlet: 'todos',
    });

I tried adding

this.render('todos.details', {
        into: 'todos',
        outlet: 'todos.details'
    });

to todo.js, but it would not work.

If you could point me in the right direction I'd appreciate it.




How can I return a well formatted 201 with Express?

I'm trying to build todoMVC with ember-cli using the DS.RESTAdapter and express to mock out the calls. The issue I'm getting is that when I try to save a new todo I see this error in the console:

SyntaxError: Unexpected end of input
    at Object.parse (native)
    at jQuery.parseJSON (http://localhost:4200/assets/vendor.js:8717:22)
    at ajaxConvert (http://localhost:4200/assets/vendor.js:9043:19)
    at done (http://localhost:4200/assets/vendor.js:9461:15)
    at XMLHttpRequest.jQuery.ajaxTransport.send.callback (http://localhost:4200/assets/vendor.js:9915:8)

I'm pretty sure the issue is that when I call save() on the newly created model, it is sending a post request to / which express is replying to with this:

 todosRouter.post('/', function(req, res) {
    res.status(201).end();
  });

Here's the create action in Ember that's creating the todo:

actions:
    createTodo: ->
      return unless title = @get('newTitle')?.trim()

      @set('newTitle', '')
      @store.createRecord('todo',
        title: title
        isCompleted: false
      ).save()

Any help would be greatly appreciated. I'm new to express and not sure why jquery doesn't like the 201 it is returning.




Ember-data relation model with controller

export default DS.Model.extend({
   slug: DS.attr("string"), 
   title: DS.attr("string"),
   body: DS.attr("string"),
   sum:  DS.attr("string"),
   human_time : DS.attr("timestamp"),
   status: DS.attr("number"),
});

This is my model while getting articles from an api, But the problem begins with post request.

Cause human_time and sum is creating by api server, not by ember. When i try to send a post request without human_time and sum, It's giving error to not getting them.

Example error:

[Error] Error: Assertion Failed: Unable to find transform for 'timestamp'

I can send via hidden input or hardcode them while sending in controller, but there are huge data to send (approx. 50 fields), how can i ignore them all? how can i tell the ember that you don't need anything except this ones.




Using Ember-CLI with MVC .Net

I am trying to use Ember-CLI and MVC .Net together. I have the ember app building with the CLI and I am trying to return View("~/ui/dist/index.html") in the MVC controller and it says

"The view '~/ui/dist/index.html' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/ui/dist/index.html"

the file is in the location so I am not sure why it is not working.

The ember app itself was working before embedded in a cshtml file, but I am migrating it into the CLI.

I was using this as a reference to setup my project http://ift.tt/1J72x0l. "ui" in the path above is the ember-cli app name




EmberJS: Object as Query Param to Refresh Model

I followed the Query Params guide (http://ift.tt/1DyrJrJ) and it worked great. Specifically, refreshing the model did exactly what I wanted.

I'm moving the filter to the json-api spec and filtering takes place in a filter object. So rather than:

http://localhost:3000/accounts?id=1

The server responds to:

http://localhost:3000/accounts?filter[id]=1

I tried to get the query params to work refreshing the model based on an object, but it doesn't seem to update.

// app/controllers/accounts/index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['filter', 'sort'],

  filter: {},
  sort: '-id'
});


// app/routes/accounts/index.js
import Ember from 'ember';

export default Ember.Route.extend({
  queryParams: {
    filter: { refreshModel: true },
    sort: { refreshModel: true }
  },
  model: function(params) {
    return this.store.find('account', params);
  },
});

// template
<th>{{input type="text" placeholder="ID" value=filter.id}}</th>

Is it possible to have query params work with an object?




How to address Model Names that are multiple words?

I am working on an Ember app in which some data is being posted to four different views. The code below works for 3 views that have single word names(Local, Business, Entertainment), but on my WorldNews view the data isn't loading.

In Chrome Ember Inspector, the WorldNews model is being called as world-news, so I'm not quite sure what I need to change in order to have the data be posted properly.

Data Info

App.WorldNews = DS.Model.extend({
    title: DS.attr('string'),
    post: DS.attr('string'),
    date: DS.attr('date')
});

App.WorldNews.FIXTURES = [
    {
        id: '1',
        title: 'Lorem ipsum dolor sit amet, consectetu',
        post: 'asdf.',
        date: new Date('1-7-2041')
    }
]

Index / World News Template

<script type="text/x-handlebars" data-template-name="worldnews">
            <h2>World News</h2>
            {{#each entries in model}}
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title" id="panel-title">{{entries.title}} - {{entries.date}}<a class="anchorjs-link" href="#panel-title"><span class="anchorjs-icon"></span></a></h3>
                </div>
                <div class="panel-body">
                    {{entries.post}}
                </div>
            </div>
            {{/each}}
        </script>




Ember Handling 401s Revisited in 2015

I can find a ton of old questions asking/answering how to handle 401s from the Rails backend in Ember/Ember Data. Many, if not all, seem to be outdated at this point. I have tried everything I could find. (Ember-Data handling 401’s)

But no matter what I do I just keep getting 401 errors in the console while the 401s are never caught in my code. All I want to do is add a redirect to '/' if a 401 is ever encountered in any place/model/anything. I don't need any checking for authentication or anything else.

I have tried adding this to the Application Route actions as well as to to the Router itself.

error: function (error, transition) {
  console.log("err: " + error.status);
  if (error && error.status === 401) {
    return this.transitionToRoute('/');
  }
}

I've also tried several variations of this http://ift.tt/1Fv3GQl.

App.ApplicationAdapter = DS.RESTAdapter.extend({
  ajaxError: function(jqXHR) {
    var error = this._super(jqXHR);
    console.log("jqXHR: " + jqXHR.status);
    if (jqXHR && jqXHR.status === 401) {
      #handle the 401 error
    }
    return error;
  }
});

I'm obviously a noob so maybe I'm missing something simple here. None of my console.log's are getting triggered unless it's for a new error I've introduced trying to get this to work. Is there a current, 'best practice' style way of doing this?




Javascript closures and memory leaks with a lot of imbricated functions and callbacks

We are building a large web applications and of course we stumbled upon the problem of having "memory leaks". Basically, when we start we have a memory usage of 90mb. We go to the second page and we get 900 mb(we are loading a lot of data).

Then, we return to the first page, and we still have around 900mb in memory.

We figured out that we probably have some leaks due to the different closures and callbacks we have inside functions. By investigating the code and looking around the web for the best possible solutions or strategies to avoid memory leaks, we found a couple of interesting articles such as these two:

http://ift.tt/1Kqwsld

http://ift.tt/1zkHIP7

Here is an example of what we have in the code:

var drawingSection_; // instantiated elsewhere but global to the file


function createSection() {
 var section = Section.create();

 section.from = drawingSection_.startPoint.data.id;

 var endPoint = drawingSection_.getEndPoint();

 var endPointData = endPoint.data;
 section.to = endPointData ? endPointData.id : '';

 Pubsub.publish(‘openView’, ‘mainView’, section, {
   endPoint: {
     lat: endPoint.leafletObj._latlng.lat,
     lng: endPoint.leafletObj._latlng.lng
   },
   click: {
     cancel: function() {
       selectedItemChanged_(drawingSection_.startPoint);
       drawingSection_.clear();
     }
   },

   callback: {
     ok: function() {
       drawingSection_.clear();
     }
   },
 });
}

Since our code is really huge, it is hard to profile everything so we basically have to manually inspect for memory leaks. In this situation, should we empty section and endpoint somewhere ? Will it make a difference? We have a pubsub that will retain a reference to section and also we have some callbacks functions that are using the data.

What is the guideline in a case like that were we have a lot of different closures ?




Ember-cli addon read configurations

I am trying to create an ember-cli addon and I want this addon to include custom command. This part I have already done by creating a lib/commands file structure and including the script that will run the command then used includedCommands in the addon index.js.

The part I am struggling with is I want the command to be able to read a configuration file within the host applications directory. How can I do this? If I could find out the host apps absolute path I suppose I could parse a file using built in node tools but how do I find this path?

If there are better ways to accomplish this task I am all ears.




Ember.js dynamic routes not resolving in test, but work in production

So, I'm trying to use the Twitter-style URL syntax, allowing a user to go to example.com/quaunaut to visit the user page of the user with the username 'quaunaut'. I was able to accomplish this via:

app/router.js

export default Router.map(function() {
  this.route('users.show', { path: '/:user_username' });
});

app/routes/users/show.js

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('user', { username: params.user_username }).then(function(result) {
      return result.get('firstObject');
    });
  },

  serialize: function(model) {
    return { user_username: model.get('username') };
  }
});

Now, when live or run via ember s, this works fantastically. However, in tests, it seems for some reason to not resolve.

var application, server, USERS;
USERS = {
  'example1': [{
    id: 1,
    username: 'example1'
  }],
  'example2': [{
    id: 2,
    username: 'example2'
  }]
};

module('Acceptance: UsersShow', {
  beforeEach: function() {
    application = startApp();

    server = new Pretender(function() {
      this.get('/api/users', function(request) {
        return [
          201,
          { 'content-type': 'application/javascript' },
          JSON.stringify(USERS[request.queryParams.username])
        ];
      });
    });
  },

  afterEach: function() {
    Ember.run(application, 'destroy');
    server.shutdown();
  }
});

test('visiting users.show route', function(assert) {
  visit('/example1');

  andThen(function() {
    assert.equal(currentPath(), 'users.show');
    assert.equal(find('#username').text(), 'example1');
  });
});

Which results in the following test results:

Acceptance: UsersShow: visiting users.show route
    ✘ failed
         expected users.show
    ✘ failed
         expected example1

So, any ideas why currentPath() isn't resolving? If you also have any recommendations for better means to implement what I'm looking to do here, I'm certainly open to it.




Firefox OS app beginner, can't import localforage properly : Could not find module `ember-localforage-adapter/adapters/localforage`

I'm currently learning how to develop a new app in Firefox OS, following step-by-step the MDN tutorial starting here : http://ift.tt/1aFegb6

Everything went pretty smoothly until the part concerning the Model, here : http://ift.tt/1HNJTMf

Specifically at the point of installing LocalForage.
I tried the first :

ember install:addon ember-localforage-adapter

And got the error message described in the tutotrial, so I tried the other command bower install localforage -v '1.2.2' It just returned the bower version.
So I tried bower install localforage alone and it worked. I got the new folder in myapp/bower_components/localforage.

The tutorial next gives the instruction to use the code :

import LFAdapter from 'ember-localforage-adapter/adapters/localforage';

export default LFAdapter.extend({
    namespace: 'ShoppingLists'
});

Aaaaand that doesn't work. I got the error message :

Error while processing route: lists.index Could not find module 'ember-localforage-adapter/adapters/localforage' imported from `'myapp/adapters/application' requireFrom@http://localhost:4200/assets/vendor.js:119:1

I didn't get the logic behind the import call, no ember-local-forage-adapter folder or something similar. I'm not comfortable with namespaces yet, but I know the theory. Is there a namespace problem somewhere I can't recognize ? Is it related to ember-data ?

I can give the full error message, but I'm pretty sure that won't help.
I did my best to figure it out alone, but I ran out of ideas, so I'm asking here.

Thank you for the help :)




Ember Project not Working Ubuntu

I am currently working on the backend of a project and wanted to pull my friends Ember front-end client to see how it looked. But, when I clone the code of git ember wont run.

I have Node installed through NVM:

arie@arie-UX32VD:~/Desktop/programming/git/uInternS/student$ which node
/home/arie/.nvm/versions/v0.12.2/bin/node

And I have tried running npm install and npm update but neither do the trick. When I run ember serve this is the response I get:

arie@arie-UX32VD:~/Desktop/programming/git/uInternS/student$ ember serve
An addon must define a `name` property.

If I generate my own new Ember project it works just fine for me to launch it. Not sure whats wrong here and couldnt find any help!

Package.json

{
  "name": "student",
  "version": "0.0.0",
  "description": "Small description for student goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "start": "ember server",
    "build": "ember build",
    "test": "ember test"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.0.2",
    "ember-cli": "0.2.3",
    "ember-cli-app-version": "0.3.3",
    "ember-cli-babel": "^5.0.0",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "0.0.8",
    "ember-cli-htmlbars": "0.7.4",
    "ember-cli-ic-ajax": "0.1.1",
    "ember-cli-inject-live-reload": "^1.3.0",
    "ember-cli-qunit": "0.3.10",
    "ember-cli-sass": "^4.0.0-beta.6",
    "ember-cli-uglify": "1.0.1",
    "ember-data": "1.0.0-beta.16.1",
    "ember-export-application-global": "^1.0.2"
  }
}

bower.json

{
  "name": "student",
  "dependencies": {
    "ember": "1.11.1",
    "ember-cli-shims": "ember-cli/ember-cli-shims#0.0.3",
    "ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
    "ember-data": "1.0.0-beta.16.1",
    "ember-load-initializers": "ember-cli/ember-load-initializers#0.1.4",
    "ember-qunit": "0.3.1",
    "ember-qunit-notifications": "0.0.7",
    "ember-resolver": "~0.1.15",
    "jquery": "^1.11.1",
    "loader.js": "ember-cli/loader.js#3.2.0",
    "qunit": "~1.17.1"
  }




How do you use Ember.js addons?

I evaluating Ember.js for possible use in an upcoming project. I want to see now it fares with a long list item, so I tried to installed the ember-list-view.

I ran the command:

ember install:addon ember-list-view

The syntax seems to have changed, so I ran

ember install ember-list-view

That activates npm, which downloaded the package successfully. I can see it in node_modules. Then per the documentation I created the following:

templates/test.hbs:

{{#view 'list-view' items=model height=500 rowHeight=50 width=500}}
  {{name}}
{{/view}}

routes/test.js

import Ember from 'ember';

// define index route and return some data from model
export default Ember.Route.extend({
  model: function() {
    var items = [];
    for (var i = 0; i < 10000; i++) {
      items.push({name: "Item " + i});
    }
    return items;
  }
});

I added the route in router.js. When I go to the page, nothing shows up. According to Ember Inspector, the right template was being used and the data was there. A check on Ember.ListView in the console yield undefined.

Is there something more that needs to be done to bring in the code? Searches in the Ember and Ember-CLI documentation yielded no answer.




Ember "select" view with 'multiple=true': underlying controller property is always 'undefined'

Ember 1.10.0 with Ember CLI 0.2.0-beta.1

I have encountered a problem with the standard "select" view (which represents an HTML drop-down list):

When the 'multiple=true' setting is applied to the view (so, the view represents an HTML drop-down list where multiple elements can be selected) I am getting the underlying controller property always having the 'undefined' value. This happens independently on the drop-down selection: either when no element is selected or just one element or multiple elements. Looks like there is no synchronization between the drop-down and corresponding controller at all.

The same with default drop-down selections (which can be set via the underlying controller property, as I know): I tried null, [], {} and some pre-selections like [1, 2]. That is not being taken into consideration at all!

The view definition in a Handlebars template:

{{view 'select'
  content=model.dictDestinations
  value=selectedDestination
  optionValuePath='content.id'
  optionLabelPath='content.name'
  multiple=true
  classNames='form-control'
}}

When the drop-down is a single-selection (no 'multiple=true' setting for the "select" view) then everything is fine.

Has anybody seen anything similar? What am I doing wrong? Or this is a bug in Ember?

Thank you!




Assertion error in Ember-data has many relationship

I am new to defining relationships in ember. Please help me on this.

This is how i am having relationships.

 App.Post= DS.Model.extend({

     comment: DS.belongsTo('comment'),
     name:     DS.attr('string')
 });

 App.Comment =DS.Model.extend({

    post: DS.belongsTo('Post'),
    value:   DS.attr('string')
 });

 App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
       comments: {embedded: 'always'}
    }
 });

Whenever i am trying to save post model, i am getting the following error:

Error: Assertion Failed: You must include an id for App.Comment in an object passed to push

I may be wrong on using embedded records. Please help me out on this. Thanks in advance.




Access target route parameters in beforeModel

How do I access the target route parameters in the beforeModel function when loading a route in Ember?

The documentation refers to beforeModel being the correct place to abort or redirect a transition - but without the target parameters I can't add the required logic to determine if we should redirect.

App.PostRoute = Ember.Route.extend({
  beforeModel: function(transition) {

    // transition doesn't seem to have the target params

  }
});

I was also unable to find any clear documentation on the Transition object described in the API documentation:

http://ift.tt/1tzsoZa




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

Doing ember -v only shows ember cli version.

How can you view ember.js version and ember data versions?




lundi 27 avril 2015

Set multiple data with Ember and make it persist on Firebase

I am trying to set data from two models (that has hasMany & belongsTo relationship) and save them to firebase.

'list' data ends up being saved to firebase but not user data.

I think I'm doing something wrong at step 3. I'd appreciate your help!

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        return this.store.find('list');
    },
actions: {
    createList: function() {
        var newListTitle = this.controllerFor('lists').get('newListTitle');
        var username = this.get('session.user.displayName');
        alert(this.get('session.user.displayName'));

        if (Ember.isBlank(newListTitle)) { return false; }

    //1
        var list = this.store.createRecord('list', {
            title: newListTitle,
            user: username,
        });

    //2
        //this.controllerFor('lists').set('newListTitle', '');

        this.controllerFor('lists').setProperties({
            title: newListTitle,
            user: username,
        });
        alert('username');

        var _this = this;

    //3
    list.get('users').then(function(users) {
        users.addObject(user);
            list.save().then(function() {
                user.save().then(function(list) {
            _this.transitionTo('lists.show', list); //4
                });
            });
    });

/*
//this was my old code when I only had one property to set
        list.save().then(function(list) {
            _this.transitionTo('lists.show', list); //4
        });
*/

        }
    }
});




How to do a random number or timestamp using link-to and query-params?

I've got a simple route that should refresh when a query-param is updated

export default Ember.Route.extend({
    queryParams: {
        refresh: {
            refreshModel: true
        }
    }
});

Because this value needs to change for the refresh to work (in the above route) I need the value in my template to be random/new each time the page is rendered. Currently I'm trying to pass the link-to a random date value like so

{{#link-to "foo" (query-params refresh=new Date().toISOString())}}home{{/link-to}}

I've even tried creating a hbs helper that will return something template friendly but I can't seem to use that in the query-params link-to placeholder.

Anyone know a way to be pure template driven and add a random number or date value for the query-param? Or even better :) I'd just like to refresh regardless of the value being updated




Right command to generate artifact in pod structure with ember-cli

What is the right way to generate items in pod structure? I am using ember-cli 0.2.3

I have my environment defined like:

module.exports = function(environment) {
    var ENV = {
        modulePrefix: 'nepal-needs',
        podModulePrefix: 'nepal-needs/pods',
        ....

I tried these:

ember g route application -p
ember g route application usePods:true
ember g route application -p userPods:true

None of it worked for me, although I remember one of these flavor worked for me before in another project!!

What strangely worked for me - although I get a warning messages is to screw up the command a bit like:

ember g route application -p:true

In my .ember-cli file, I have set "usePods" to true like

"usePods": true

Here is the screen shot:

enter image description here

So what is the proper way to generate files?

UPDATE : turned out the complied app was not working even though I was able to get the filed in pod structure. Its throwing error:

throw new Error('Could not find module ' + name);




Ember best practice: Mixin vs Component

I have component B that extends from component A, also I have component D that extends from component C. Between B and D there is some share code to upload to s3 but they actually aren't much related. Still I don't like the code duplication but I don't know if I should:

  1. Write a mixin and import in both components.

  2. Make a component for this shared code an import it on the other components.

What would be the ember way to do this?




How does the SANE stack represent parent/child relationships on a single model

How do I represent a parent/child relationship on the same model?

An example of this is a model representing a folder. A parent folder can have many children folders. But a child folder can only have one parent folder.

Ember.js has the concept of reflexive relations. I would like to implement the first option.

"... explicitly define the other side, and set the explicit inverse accordingly ..."

How would I go about setting that up on the sails.js side of the SANE stack?




In Ember how can I have different html in a component used in multiple places?

I'm trying to make a dropdown component that can have different HTML in the heading/title. I have this so far:

component:

App.TestShowComponent = Ember.Component.extend({
  layoutName: "components/test-show",
  expanded: false,
  actions: {
    toggle: function () {
      this.set('expanded', !this.get('expanded'));
    }
  }
});

index template:

{{#test-show}}
  inner stuff
{{/test-show}}

component template:

<button {{action 'toggle'}}>toggle</button>
{{#if expanded}}
  {{yield}}
{{/if}}

But what I need is for the heading markup where the button is, I'd like that to be able to be passed in somehow so that I can use different markup for the headings of different dropdowns on the page. For example the heading of one dropdown may be an image and then somewhere else on the page I use the component again but this time with the heading as a button.

Is this possible or would I have to make separate components like {{button-dropdown}} and {{image-dropdown}}