dimanche 31 mai 2015

Backbone integration tests: looking for helpers like Ember's

I've been looking at Ember's test helpers for integration testing and some example tests like here. I would like to write tests for a Backbone.js app I am maintaining in a similar manner. I have looked at tools such as Chai and Sinon and got the feeling that these produce a much more convoluted testing code and are hard to maintain.

  • Are there any similar libraries such as the Ember helpers for Backbone
  • Is there any reason why no one has written such helpers?



creating an ember-data application serialzer

I've been trying to use ember data for a few days now. The problem is the api I have does not match the strcuture ember-data would like to receive.

item:

{
    "data": {
        "id": 1,
        "username": "rodzzlessa",
        "slug": "rodzzlessa"
     }
}

collection:

{
"data": [
    {
        "id": 34,
        "name": "HDG common nails 50lbs",
        "slug": "hdg-common-nails-50lbs4569",
        "description": "Accusantium ipsam impedit omnis sint dolorum.",
        "image_src": "nail-box-angle.png",
        "categories": {
            "data": [
                {
                     "id": 2,
                     "name": "nails",
                    "image_src": "nails-icon.png"
                }
             ]
         }
     }
  ]
}

from what I've seen I need to modify the extractSingle and extractArray methods. There really isn't an online resource showing what the methods are really doing and how to modify them. I check the ember-data api guide but the example is so specific and its not an application serializer so it seems much easier the problem they are solving. I tried finding an ember-data book but they don't exist yet. Are there any online resources to help me?




Loading mongodb data into an emberjs web application

I'm trying to import data from a mongodb server and presenting it in my emberjs web application using emberjs and ember-cli build tool.




Ember-cli unable to access dynamic routes model

Router.map(function() {
  this.route('projects',     function() {
    this.route('project', { path: '/:project_id' }, function() {
        this.route('cards');
        this.route('new',{ path: '/cards/new' });
    });
  });
});

Forder structure: app

   --/routes
     --/projects
       --/project.js   
       --/project
           --/cards.js
           --/new.js

I can access the dynamic segment :project_id in cards.js route like this

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(){
    var project = this.modelFor('projects/project');
    return project.get('cards');
  }
});

but same code is not working for route new.js i.e not able to access project model

import Ember from 'ember';

export default Ember.Route.extend({
    actions: {
        addCard: function() {
            var project = this.modelFor('projects/project');
            console.log(project); //this is printing projects array I was expecting single current project model
        }
    }
});

//my project route looks something like this

import Ember from 'ember';

export default Ember.Route.extend({
    setupController: function(controller,model) {
        this._super(controller, model);
        controller.set('projectList',this.store.find('project'));
    },  
    model:function(params) {
        return this.store.find('project',params.project_id);
    }

});




Ember Cli on windows

I m trying to get Ember cli on Windows 7.I have installed node and npm. But when I type npm install -g ember-cli I get the following error.Is there anything that I am missing?enter image description here




Use different components depending on a property of a model

In my Ember app I created one model with a color property

   App.Gecko = DS.Model.extend({
       color: fusia

    })

In the templates, I want to run different components depending on the color of the Gecko, so the desired logic in my templates is like this

 {{#each item in model}}
       {{if item.color == green}}
             code for a component
       {{/if}}
       {{if item.color == blue}}
            code for some other component
       {{/if}}
 {{/each}}

Except that Handlebars doesn't support the {{ if item.color == green }} logic. I understand that I'm supposed to use computed properties for this, but I can't figure out how to set it up so that different components would run depending on the color of the item. Question: How would I use a computed property on my controller (I'm assuming it belongs in the controller) to run different components depending on a property in the model?




how to add event for drop-down component to change subdomain by selected item

i use pod structure with ember cli. i have a 'drop-down' component.

in my drop-down.js component:

import Ember from 'ember';
var component = Ember.Component.extend({
tagName: '', //remove extra div wrapper.
valueKey: 'id',
textKey: 'text',
options: [],
value: null,
defaultText: 'select...',
selected: function () {
var valueKey = this.get('valueKey');
var textKey = this.get('textKey');
var defaultText = this.get('defaultText');
var fallbackOption = {};
fallbackOption[valueKey] = 0;
fallbackOption[textKey] = defaultText;

if (Ember.isEmpty(this.get('value'))) {
  return fallbackOption;
}

var selected = this.get('options').findProperty(valueKey,this.get('value'));

return selected ? selected : fallbackOption;
}.property('options', 'value'),
 actions: {
 select(option) {
  var valueKey = this.get('valueKey');
  this.set('value', option[valueKey]);
  }
  }
});

export default component;

i have used this component in index to load countries.

in template.hbs for index :

 <div class="col-lg-3 col-md-3 col-sm-3 col-xs-6 input-padding">
              {{drop-down options=model.countries
              value=country
              valueKey=valueKey
              textKey=textKey
              defaultText=defaultText}}
            </div>

i want to add change event to countries dropdown, that it must change subdomain by country. for example, when i select Iran, its event causes my subdomain changes to 'Iran.site.com. how can i add this event? and where should i add it ?thanks




samedi 30 mai 2015

Building an one page app: framework choice

I have a client needs a web app with a one-page homepage, as well as user system and database. Something similar would be https://www.chegg.com/

I plan to use Rails as backend. What would be the ideal javascript framework for the one-page homepage? I know there're things out there like backbone, angular, ember, bootstrap etc. I don't have experience with any of them. Which one would you recommend considering easy to pickup and documentation available? The priority is to get the job done.

Thanks!




How can I delete a chat message with Emberfire?

I've created an action to add messages to my firebase, but can't seem to figure out how to remove a specific message. Here is my new message controller so far:

import Ember from 'ember';

export default Ember.Controller.extend({
//define actions here
actions: {
    addMessage: function() {
        //createRecord creates new instance of message model
        var newMessage = this.store.createRecord('message', {
            //this gets the info from the form fields with this value
            name: this.get('name'),
            body: this.get('body')
        });
        //this saves the data to store and firebase
        newMessage.save();
        //this resets the fields to be blank again
        this.setProperties({
            name: '',
            body: ''
        });
    }
  }
});

and this is my message controller with the remove action

import Ember from 'ember';

export default Ember.Controller.extend({
actions: {
    deleteMessage: function(id) {
        var msg = this.store.find('message', id, {
            //this gets the info from the form fields with this value
            name: this.get('name'),
            body: this.get('body')
        });
        //this deletes the data to store and firebase
        msg.remove();
    }
}
});

and here's my template

<div class="new-msg-link">
    {{#link-to 'messages.new'}}Add New Message{{/link-to}}
</div>

{{outlet}}

{{#each message in model}}
    <div class="each-msg">
        {{message.name}}: {{message.body}}
        <button {{action 'deleteMessage'}}>Delete</button>
    </div>
{{/each}}

I'm not sure how to pass the id parameter in my action correctly and how to get it from firebase correctly. Any suggestions would be great! thanks




Hanlding access control in ember routing

I have two routes in this app that are backed by models that have access control logic on the rails side. So when they first load into the application, they've got an isUnlocked property that I check after the model loads. If the property is not unlocked, the route should redirect.

So if my router is something like:

this.route('thing', { path: 'thing/:thing_id' }, function() {
  this.route('resource', { path: 'resource/:resource_id' });
});

And my "resource" route extends something like this:

import AuthenticatedRoute from 'doki/routes/authenticated';

export default AuthenticatedRoute.extend({

  requireDean: false,

  activate() {
    this._super();
    this.checkAccess();
  },

  afterModel() {
    this._super();
    this.checkAccess();
  },

  resetController() {
    this._super();
    this.checkAccess();
  },

  checkAccess() {
    // here is where I'll check the model's isUnlocked property and 
    // redirect if it's false or not set
    console.log('checkAccess');
  }

});

When I enter /thing/1/resource/1, the model for resource=1 is loaded by the ThingResourceRoute, but if resource=2 is already loaded in the store, if I click over to /thing/1/resource/2, activate doesn't fire, setupController doesn't fire, etc, so I'm not sure where to do the checkAccess() test.

What's the best place to check the isUnlocked property whenever the URL changes, because "activate", "resetController", et al, don't fire when the URL changes to the same route but a different item that has a different isUnlocked property.

Is there a hook that I can implement that will always be called? Putting an access check in renderTemplate seems like it'd work, but that doesn't seem like the right place.

Should I just invalidate the model after updating the model via an API call? If I set isUnlocked to true locally (and don't persist the model via the API), where would I add the check for that in the route/controller chain that it would always check every time it tries to "access" that model?




Extra information in `loading` substate

I have an Ember app. In a given route, I have a handcrafted model that is not loaded immediately. Thus, I hand it over as a promise:

export default Ember.Route.extend({
  model() {
    return MyModel.create().promise();
  }
})

Don't worry too much about how MyModel works. The important bit is that it returns an RSVP promise.

As a result, Ember transitions to a loading route. There, I have a template that renders correctly showing a spinner, transitioning to the correct route once the promise is resolved.

My question is: how can I show real progress? MyModel does something relatively complex, with several steps, and I would like to show actual progress on these steps. Instead of a stateless spinner, I would like to show stateful progress. MyModel (or rather, its promises) knows about its progress, but I don't know how to communicate it down to the template.

I implemented a route and a controller for this loading state. Both load correctly, but neither seems to have access to anything that may help here. In fact, I can't see that RSVP promises even have a progress handler, like other libraries do. Am I missing something?




Ember not creating an id for new instances

I created a prototype of an Ember app using the Local Storage adapter that I am not trying to port to using the REST adapter with a backend store. In the local storage version, I noticed that Ember creates an id for an new instance of a model prior to the instance being saved (and also even if the instance is never saved). For example, in my local storage app, I can log the id in both places

var gecko = this.store.createRecord('gecko', {
    date: new Date(),
    type: "gecko",                                     
    });
  console.log(gecko.id, "gecko.id before save");
  gecko.save();
  console.log(gecko.id, "gecko.id");

By contrast, in the version that I'm making with the REST adapter for the backend store, the there is NO id being logged, and when I check the data that Ember is trying to send to the server, it is not sending the id (because one was probably never created). Here is the json that Ember is sending to my server

  gecko: { type: "alloc", date: "2015-05-30T13:28:27.539Z"}

My assumption was/is that I am supposed to save the id that Ember creates on my server (which would of course allow it to retrieve the record by id provide my server implements that).

Question: why is there no id being created?

this is the code

    App = Ember.Application.create();

    App.Router.map(function() {
      this.route("gecko", { path: "/" });

    });
    App.ApplicationAdapter = DS.RESTAdapter.extend({
    //haven't actually any created any code for this part yet
    });
    App.ApplicationStore = DS.Store.extend({
      adapter: App.ApplicationAdapter.create() 
    });
    App.Gecko = DS.Model.extend({
      type: DS.attr('string'),
      date: DS.attr('date')
    })
    App.GeckoRoute = Ember.Route.extend({

      model: function() {
       //currently does nothing. originally I tried to do `return this.store.find('gecko') but since there are no records yet on the backend, it's returning null which leads to an error which Array cannot map over
      },
    });
App.GeckoController = Ember.Controller.extend({

  actions: {
       createGeckoButtonClicked: function(){

            var gecko = this.store.createRecord('gecko', {
                date: new Date(),
                type: "gecko",                                     
            });
            console.log(gecko.id, "gecko.id before save"); //null
            gecko.save();
            console.log(gecko.id, "gecko.id"); //null
       }


  }

Note- not sure if it's relevant, I feel like I'm in a chicken/egg situation with the route where I can't return any entries because I haven't created any yet. so therefore, I'm trying to setup the ember app to be able to POST an entry to the server, then I will implement the route to retrieve it using return this.store.find('gecko'). As mentioned already if I do return this.store.find('gecko') with no entries in the db, it throws an error because array.prototype.map called on null or undefined




vendredi 29 mai 2015

Formatting Controller Response in Rails with Ember $.getJSON request

Disclaimer: New to Ember (and by no means a seasoned Rails dev)

I am building a simple Ember app using a Rails backend to query a third party API. My controller is receiving the params from the GET request, but I get a 500 error telling me that I am calling a render/redirect multiple times in this action. I really want a JSON response sent back to my Ember controller.

// Ember controller

export default Ember.Controller.extend({

  actions: {
    getGif: function(){
      $.getJSON("http://localhost:3000/gifs?q=cats", function(result){
       var embedGif = result
        $('#some-id').append(embedGif);
      }) 
    }
  }
});


class PostController < ApplicationController


  def gifs
    searchterm = params[:q]
    split_string = searchterm.split(" ")
    if split_string.length > 1
      slug = split.string.join("+")
    else
      slug = searchterm
    end
    response = HTTParty.get("http://ift.tt/1LSTq4y")
    response["data"].each do |gif|
      url = gif["images"]["fixed_height"]["url"] 
    respond_with(url) |format|
        format.json
    end
    end
  end
end




Ember Fastboot and the pods structure

A question about the Ember Fastboot and the pods structure. Is there any reason why would it not work together? Have anyone tried it?




Build dynamic relationship in ember data

I have access to API endpoints to only get, cannot suggest or apply any modifications.

This a sample schema of each api:

var person = DS.Model.extend {
    firstName: DS.attr(),
    lastName: DS.attr()
}

var credit = DS.Model.extend {
    name: DS.attr(),
    personId: : DS.attr()
}

var debit = DS.Model.extend {
    name: DS.attr(),
    personId: : DS.attr()
}

I can get api/person, api/credit, api/debit individually. After fetching the data. I want to map relationship between person and credit/debit similar to this...

var person = DS.Model.extend {
    firstName: DS.attr(),
    lastName: DS.attr(),
    **debits: DS.hasMany('debit'),**
    **credits: DS.hasMany('credit')**
}

How can I accomplish this in ember-data?




Ember JS | How is ember differentiating Router resource and a route?

Ember makes use of the router.js to load a resource and its corresponding template into the application template. But what happens when a particular route is accessed? i.e How will ember get to know that we are accessing a route but not a resource?




Populate a select box with results generated from another select box

Another new-to-ember question - I have a component that contains a select (call it type) object. When a type is selected, I want to take the selected type, make a REST call using the selected type to return records, and populate a second select object in another component with the returned records. There are too many subtypes to get during initialization (the type list is retrieved during initialization). The process currently is: 1) select value type is chosen 2) type chosen is sent to parent route and set there 3) value chosen is used by REST service to get list of subtypes. All this works now, but I have been unable to set the the component select to the subtypes retrieved by the REST service. Been beating my head against this for a while now, so any help would be appreciated. Thanks.




Customizing PUT route on save method in ember.js

I would like to manually specify a PUT route for saving my model. Is this possible with ember?

For example, I have a conversation model and when I call conversation.save(), I don't want it to search for the PUT conversations/someMail/conversations/:id but to manually tell ember to use PUT /conversations/:id instead.

Here is my namespace :

App.ApplicationAdapter.reopen({

namespace: 'conversations/someEmail'

});

Router :

App.Router.map(function(){

//Routing list to raw namespace path
this.resource('conversations', { path : '/' }, function() {
    this.resource('conversation', { path : '/:conversation_id'});
});

});

Model :

App.Conversation = DS.Model.extend({

readStatus: DS.attr('string'),
url: DS.attr('string'),
status: DS.attr('string'),
lastMessage: DS.attr('string'),
createdAt: DS.attr('string'),
timeAgoElement: DS.attr('string'),
customer: DS.belongsTo('customer'),
content: DS.attr('array'),

});




broccoli Brocfile import a function

I have the Brocfile importing other assets but I'd like it to import an array of files from a directory. I tried this:

var theComponents = function(){ return fs.readdirSync(__dirname + '/addon/components')}()
console.log(theComponents)
app.import(theComponents)

But it's not converting as I'd like it to. I understand that the vendor.js is usually static files, but I'd like to compile the array as if it was a static file of an array. How can I do that?




How to call components inside a components with pods structure in ember cli

I have 2 components x-foo and y-foo in a pods structure.

app/pods/components/x-foo/template.hbs app/pods/components/y-foo/template.hbs

I want to call y-foo component inside x-foo component's template.hbs like this:

<section>
  {{y-foo}}
</section>

But it errors out saying that y-foo helper doesn't exist. Can anyone show me the right way to do this in a pods structure?




Why is a "ManyToOne" relation treated differently when serializing in ember-data?

My question is highly related to "Ember Data: Saving relationships" but I don't care about embedding - I just want a working OneToMany (bi-directional) relationship. Take for example the following models:

App.Child = DS.Model.extend({
    name: DS.attr('string'),
    toys: DS.hasMany('toy'),
});
App.Toy = DS.Model.extend({
    name: DS.attr('string'),
    child: DS.belongsTo('child')
});

and the following object creations/saves:

var store = this.get('store');

store.createRecord('child', {name: 'Herbert'}).save().then(child => {
    store.createRecord('toy', {name: 'Kazoo', child: child}).save().then(toy => {
        child.get('toys').pushObject(toy);
        return child.save();
    });
});

I would expect the child, when serialized to reference the toy. E.g. something like

{
   'name': 'Herbert',
   'toys': [ 1 ]
}

But it doesn't. Because this is a "manyToOne" relation ship and ember-data won't serialize these: http://ift.tt/1J8GUQE

If you make it a ManyToNone relation by removing the belongsTo it will work but you will lose the back reference.

Why is this special behaviour? Why is ManyToOne that different from ManyToNne or ManyToMany that it deserves such special treatment?

Where is this behaviour documented? I totally missed it and assumed it was a bug in the Serializer / Adapter I'm using.

What is the correct way to achieve my desired serialization?




EmberData Setting value prevents future autoloads of data after model save

In EmberData calling model.save() causes the model to be persisted via whatever adapter is in place. If the adapter returns some data (such as JSON from an API) the model is updated with that data.

I have stumbled upon a sequence where this is not true.

In a voucher system for a checkout process a voucherCode is entered on an order model. When an 'Apply' button is pressed the order is saved via order.save() and the voucher is thus submitted to the server.

If the voucher code is valid a voucherValue field is populated with a number. If the voucher code is invalid a 422 error is returned with a standard errors object as per http://ift.tt/1kd5W52

Now, here is where things go awry. If a code is entered that returns a voucherValue of 300 a controller property calculates the discount.

discount: function () {
  var discount = this.get('model.voucherValue');
  // some calculation
  return discount;
}.property('model.voucherValue')

If, for whatever reason, the user then enters an invalid code we return an error as described above. The server removes the discount and sets the voucherValue to 0

As the error response does not contain the updated data in the catch of the save we manually update it.

order.save().then(function () {

}).catch(function (error) {

  order.set('voucherValue', 0);
});

The discount computed property is updated as expected on setting the voucherValue. However, inspecting the order model shows that order._data.voucherValue is still the original 300 value from the first valid voucher code - as EmberData does not know this value is persisted on the server.

If we then enter a valid voucher code that returns a voucherValue of 300 (the same as it was originally) the discount computed property is not recalculated.

It appears Ember is checking the returned data values against order._data and as there is no difference is not triggering any property recalculations.

I've tried different workarounds but have been unable to find something that works reliably.

Frustratingly there does not seem to be a reliable way to access the returned data and manually set the voucherValue from the returned data. Even if the returned data sets a value for voucherValue the following is true:

order.save().then(function (savedOrder) {

  savedOrder.get('voucherValue') === 0; //true

}).catch(function (error) {
  order.set('voucherValue', 0);
});

However, if a different voucher is entered after an invalid voucher and the voucherValue is different (say 450) everything works as expected.

Is this a bug in EmberData? Is there a know workaround. I'm open to suggestions and willing to try anything before I try and reengineer how this entire system is implemented.




Ember createChildView documentation?

I'm looking for documentation for createChildView of Ember.js version 1.6.1 but I can't find anything.

More precisely I'd like to know the purpose of the target property, I don't get the purpose of it, should it set the target controller or the target node where to put the ChildView?




Ember: Helper inside Component renders undefined

I have component which renders a grid and it uses a helper to render each row. I'm getting undefined instaed of actual data. If I directly render the data without the helper the actual data is rendered. Please find the code below

Gird Comp

{{#each data in dataValues}}
    {{ log " grid-comp "  data.title //title is rendered correctly}}
    {{grid-row data}}
{{/each}}

Grid Row Helper

export function gridRow(data) {
    console.log(data.title); //undefined
    var row;
    row='<tr><td>'+data.id+'</td><td>'+data.title+'</td><td>'+data.publishDate+'</td><td>'+data.comments+'</td></tr>';
    return new Ember.Handlebars.SafeString(row);
}

Note: The data comes from the Fixture




jeudi 28 mai 2015

ember-cli migration: global app module import

I'm having some slight ember-cli migration difficulties with the global application variable.

In project/app/app.js I define App as:

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

Then in a separate controller, project/app/controllers/auth.js, I attempt to access App using the following statement:

import Ember from 'ember';
import App from '../app.js';

This results in an extremely odd error from when running the application. I receive the following error from the Chrome inspector (or Firebug):

Uncaught Error:  Could not find module 'project/app.js' imported 
from 'project/controllers/auth'

At first glance this appears to be a path error in my import statement. However, efforts to fix the path have proven useless. Then I also noticed that the imported portion of the error was not including the correct path either! It should read project/app/controllers/auth but instead reads project/controllers/auth. I'm quite confused as to what's happening here.

Please let me know if I can provide more details at all, thanks so much!




Counting model with ember data

I've looked at various examples on Stackoverflow but I don't seem to understand how get('length') really works.

I'm trying to get a count of users in helper model. There is probably something wrong with the way I'm trying to get('length'), but maybe I also need to use hash RSVP to get both the current model and helper model in todo route?

todo.js

export default Ember.Controller.extend({

    count: function() {
        var helper = this.get('helper');
        return helper.user.get('length');
    }.property('helper.user.[]'),

todo.js

export default DS.Model.extend({
    title: DS.attr('string'),
    isCompleted: DS.attr('boolean', {defaultValue: false}),

    list: DS.belongsTo('list', {async: true}),
    user: DS.belongsTo('user', {async: true}),

    comment: DS.hasMany('comment', {async: true}),
    helper: DS.hasMany('helper', {async: true}),
});

todo.hbs

<p>
                    <span class="badge pull-left">14 hands</span>
                    <span class="badge pull-left">{{todo.count}}</span>
                    </p>

helper.js

export default DS.Model.extend({
    user: DS.belongsTo('user', {async: true}),
    todo: DS.belongsTo('todo', {async: true}),
});

todo.js

export default Ember.Route.extend({
  model: function(params){
    // return model
  },




Error processing route when using modelFor in model hook

I have a route structure as follows:

this.route('brands', function() {
  this.route('brand', { path: ':brand_id' }, function() {
    this.route('items', function() {
      this.route('item', { path: ':item_id' });
    });
  });
});

Inside my items route I have the following model hook:

var brand = this.modelFor('brands.brand');
return brand.get('items');

When I start at the brand route and navigate towards an item route and then back to the items page, everything is fine. But, when I refresh at an item route and navigate back to the items route, Error while processing route: brands.brand.items.index is thrown.

I tracked it down to these two possible workarounds:

1) Use the following model hook on items:

let brand = this.modelFor('brands.brand')
return this.store.find('item', { brand: brand.id });

2) Comment out the brand relationship on the item model.

Ember isn't really helping here with a meaningful error message. All I can see is some arcane rejected promises like:

Router: 'application.brands.brands.brand.brands.brand.items.brands.brand.items.index': Resolve handler.

I'm using Ember 1.12.0 with Ember Data 1.0.0-beta.16.1.




configuring server and client ports in Ember-Cli in different environments

I am making an Ember app using Ember-Cli which talks to a server side application. Because Ember-Cli projects run with their own server (on port 4200 by default), I have to run my server in development on a different port (localhost:8080) than the Ember app. In production, however, the two will be running on the same port. Question: How can I configure Ember (in config/environment.js I presume) so that Ember-Data and all ajax requests will be made to localhost:8080 in development (in spite of the fact that the Ember app is running on 4200) and, in production, that Ember-Data and ajax requests will query whatever port the server side app is running on (which will be hosting the client side app).

Ember-Cli docs mention that some configuration can be done (for example that you can change the port that Ember-Cli runs on), however, it doesn't say how to accomplish the above




Ember CLI load vendor js after app is loaded

I have third party assets under the vendorfolder and it's compiled into <script src="assets/vendor.js"></script> on page load. However it is being loaded before the ember templates are rendered/created. Wondering if there is a way to load vendor assets after the ember app is fully loaded.




Disabling click triggering on a checkbox inside a div with a click event in Ember

I have divs created with a #each loop. Each div have a click action and contains a checkbox. I want to prevent the checkbox from triggering the click event of its parent div. I am using Ember.js handlebars.

<script type="text/x-handlebars" data-template-name="conversations">   
    {{#each conv in model itemController='singleconv'}}
            <div class="conversation-content-wrapper" {{action "clickConv" conv preventDefault=false}}>
                    <div class="history-message-assigned in-progress-closed" style="display:none;"><p><i class="icon-x"></i>Conversation closed</p></div>
                    <div class="history-message-assigned in-progress-assignation" style="display:none;"><p><i class="icon-assign"></i>Conversation assigned</p></div>
                    <div class="history-message-assigned in-progress-reopen" style="display:none;"><p><i class="icon-re-opened"></i>Conversation re-opened</p></div>          
                <div class="conversation-history">          
                    <div class="conversation-time-history">{{{conv.timeAgoElement}}}</div>
                    <div class="conversation-details">
                        <span class="unread-numbers"></span>
                        {{input type='checkbox' checked=conv.isChecked bubbles="false"}}
                             <span class="conversation-name">{{conv.customer.name}}</span>
                             <span class="phone-number">{{conv.customer.cellPhoneNumber}}</span>
                            <p class="conversation-text">{{conv.lastMessage}}</p>
                    </div>
                </div>                       
            </div>
    {{/each}}     
</script>

What is the most efficient way to do so? I did look onto the bubbles="false" attribute, but either I don't put it at the right place or it isn't made for this case.




EmberJS | How is outlet loaded inside application.hbs

I am new to EmberJS, Can someone please explain how does EmberJS loads the outlet in side application.hbs?

I know applicaiton.hbs is the starting point, from where the router.js will invoked that will call the default resource. I am lost on how the default resource loads another template into the applcation.hbs




In Ember.js, what is the proper way to get the current controller?

Currently, I have a mixin adding currentController property you can use to get the controller for the current route. I need it to be bindable so this is my code:

// client controller should be adding 'application' to its needs array
export default Ember.Mixin.create({

  _appController: Ember.computed.alias('controllers.application'),

  currentController: function () {
    var currentRouteName = this.get('_appController').get('currentRouteName');
    return this.controllerFor(currentRouteName);
  }.property('_appController.currentRouteName')

});

But the use of controllerFor is deprecated in favor of needs. So, how should I do? Thank you.




When to use controllers when using components with Ember

In the latest (1.10+) versions of Ember there seems to be a trend to make use of components instead of controllers and views.

The wisdom seems to be: "Only use controllers at the top-level for receiving data from the route, and use Ember.Controller instead of Ember.ArrayController or Ember.ObjectController"

This makes some sense to me as it's cool to create reusable components, but there are some scenarios where it is unclear to me what the appropriate approach is.

Say we have a component which represents a row in a table, something like this:

# entry-row.js component
import Ember from 'ember';

export default Ember.Component.extend({
  tagName: 'tr',

  actions: {
    toggleResolving: function() {
      this.toggleProperty('resolving');
    }
  },

  isChecked: function() {
    return this.get('resolving');
  }.property('resolving')
});

# entry-row.hbs template
<td {{action "toggleResolving"}}>{{entry.name}}</td>
<td>{{entry.currency.symbol}}{{entry.amount}}</td>
<td>{{entry.date}}</td>
<td class="bs-checkbox">{{input type="checkbox" checked=isChecked class="toggle"}}</td>

To form a table, many of the same component are used. That's great. If there is some non-persistent state which applies only to that row then that can belong to the component and be changed there. Something like:

actions: {
    toggleResolving: function() {
      this.toggleProperty('resolving');
    }
  }

But say that my resolving property is also useful outside the component. In this case, I wish to be able to mark several rows for resolution and then perform some action on them collectively. I believe that before the switch to components, I would have defined the resolving property on the Controller and made use of that controller wherever I needed the model + state.

Should I still be putting this on the controller?




Add additional model to model hook triggered from link-to

I'm happy that multiple models can be loaded into a route using something like this (although feel free to correct if there's a better way!):

 model: function() {
        var self = this;
        return Ember.RSVP.hash({
            foos: self.store.find('foos'),
            bars: self.store.find('bars'),
        });

However, if the model hook is set by a model being passed by, for example, a link-to helper, how should I add the additional model?

Thanks!




Ember 1.12 now requiring me to use mode.propertyName rather than accessing properties directly

Just upgraded to 1.12, and where I had a project route that returns a single project from the store, previously I could access the properties of that model directly like {{projectName}}, but now I have to use {{model.projectName}}. can anyone shed light on what's going on?

Link-to from my projects route:

{{#link-to 'project.details' project.id title="Go to project details"}}

Model hook in project route:

model: function(params) {
  var record = this.store.getById('project', params.project_id)
  if(record) {
    return record.reload()
  } else {
    return this.store.find('project', params.project_id)
  }
}




Fixing Initializers deprecation in Ember 1.12.0

I am refering to this particular depreacation that was introduced in Ember 1.12

lookup was called on a Registry. The initializer API no longer receives a container, and you should use an instanceInitializer to look up objects from the container

I looked at the guide, but I am unsure on how to fix this.

Here's a snippet of the code I have at the moment

initialize = (container, app) ->
  auth = container.lookup('auth-manager:main')

  local_config = ($.ajax
    type: 'GET'
    url: '/config.json'
    async:false
  ).responseJSON

  external_config = ($.ajax
    type: 'GET'
    url: local_config.crm.provisioning.url + '/v1/configurations'
    dataType: 'json'
    headers:
      'Authorization': auth.get 'token'
      'Accept': 'application/json'
      'Content-Type': 'application/json'
    async: false
    error: (e)->
      if e.status == 401
        window.location.href = window.location.origin + '/auth.html?src_url=' + window.location.href
  ).responseJSON

ConfigInitializer =
  name: 'config'
  after: 'auth-manager'
  initialize: initialize

The problem is that I require the auth-manager initializer in order to initialize my config initializer. Most of my other initializers require both the config and auth-manager initializers to get an access_token and connection endpoints.

In a ember-cli project should there be one file for the instance initializer and one for the registration of the initializer ?

The example given in the ember doc really confuses me.




Problems rendering script tags in script tags with handlebars

I want to render templates inside my application template. I'm using handlebars with ember.js. Right now I am using a simple {{render 'templateName'}} but this seems to mess up the html/css of the page. I tried using {{partial 'templateName'}} for rendering but my templates won't render at all.

To put it in a simple way, the div are messed up. What is the correct way to render handlebars template in handlebars templates?

Here is an example of what I am doing :

<script type="text/x-handlebars">
    **Some html**
    {{render 'conversations'}}
</script>

<script type="text/x-handlebars" data-template-name="conversations">   
{{#each conv in model }}
    {{#link-to 'conversation' conv}}  
        <div class="conversation-content-wrapper" {{action "click" conv}}>
                <div class="history-message-assigned in-progress-closed" style="display:none;"><p><i class="icon-x"></i>Conversation closed</p></div>
                <div class="history-message-assigned in-progress-assignation" style="display:none;"><p><i class="icon-assign"></i>Conversation assigned</p></div>
                <div class="history-message-assigned in-progress-reopen" style="display:none;"><p><i class="icon-re-opened"></i>Conversation re-opened</p></div>          
            <div class="conversation-history">          
                <div class="conversation-time-history">{{{conv.timeAgoElement}}}</div>
                <div class="conversation-details">
                    <span class="unread-numbers" data-badge="2"></span>
                        <input type="checkbox" name="conversations_ids[]" value="{{conv.id}}" />
                         <span class="conversation-name">{{conv.customer.name}}</span>
                         <span class="phone-number">{{conv.customer.cellPhoneNumber}}</span>
                        <p class="conversation-text">{{conv.lastMessage}}</p>
                </div>
            </div>                       
        </div>
    {{/link-to}}
{{/each}}     
</script>




Ember - where to put the public site

I'm wrapping up my Ember application and I want to figure out the best practice for handling the public site (/, /about, /faq, etc). Ideally the Ember JS and the majority of the app itself wouldn't be loaded.

There are a couple options, but I'd like to know the best practice.

Option 1 - Part of the app

Just make the public pages templates within ember-cli.

Pros:

  • Same asset pipeline
  • Single delivery of your entire site

Cons:

  • How do you have two base templates? One for the public site and one for the app itself. Ideally I'd be able to have different nav bars for each part. Everything inherits from the application.hbs template but I don't want to put conditionals in there to handle the two nav bars. I also don't want to overwrite every other page in my app to put it under a different template (/app/*).
  • The entire app would be loaded the first time the user goes to the page (only gets slower as the app gets bigger).

Option 2 - Part of the public folder

Create static HTML in the /public folder.

Pros:

  • Same asset pipeline
  • Single delivery of your entire site
  • Not loading the entire app for public pages

Cons:

  • You have the write the entire HTML for every page. This doesn't allow for quick development.
  • No template system. As the public site grows it's best to have a template so you can easily change the nav bar on all pages.
  • Not sure how to handle / since ember-cli wants to handle that url, but I'd want it to be apart of the public site.
  • Adds a lot of junk to your public folder since you'd need to add about/index.html for good urls.

Option 3 - Separate from the ember-cli project/app

Create a nanoc site or some other statically generated site and deliver it for your public pages.

Pros:

  • Have properly layouts for public site
  • Separation of assets
  • Not loading the entire app for public pages

Cons:

  • Need to figure out how to properly deploy separate apps on the same domain (putting ember-cli under /a/ is easy, but if I deploy to heroku how do I serve up multiple heroku apps on the same domain?).
  • How should /sign-up and /sign-in be handled? Public site with public site chrome, or web app with a signed out state (not ideal).



Show block if resource is 'active'

I have a list of items. If I click the link-to for the item, I want the item itself to expand showing more info.

What I'd like to do, is in the #each loop, add an if conditional:

{{#each item in model itemController="item"}}
    {{item.title}}
    {{#if item.active}}
        {{item.description}}
    {{/if}
{{/each}}

The item.active is only true if the route for that item is met via a link-to or transitiontoroute. What am I missing here?




EmberJs ember-data with ember-localstorage-adapter

Im using REST adapter by ember-data and it works fine. But now I want to use local storage for user settings storing.

Please, explain me, what is the right way?

I'm using ember-cli.




Ember Mixin actions

I am trying to develop my first mixin. I want my controllers to be able to toggle an editing property and to set it to false when the model is saved or rolled back.

in myapp/mixins/editable.js:

import Ember from "ember";

export default Ember.Mixin.create({
  editing: false,

  actions: {
    toggleEditing: function() {
      this.toggleProperty('editing');
    },
    cancel: function () {
      console.log("editable mixin: cancel");
      this.set('editing', false);
      return true;
    },
    save: function () {
      console.log("editable mixin: save");
      this.set('editing', false);
      return true;
    }
  }
});

I thought this would be great as I can have consistent edit buttons in my templates like this.

in myapp/templates/sometemplate.hbs:

{{#if editing}}
  {{#if model.isDirty}}
    <button class="action-icon" {{action "cancel"}}>{{fa-icon "times" title="discard changes"}}</button>
    <button class="action-icon" {{action "save"}}>{{fa-icon "save" title="save changes"}}</button>
  {{else}}
    <button class="action-icon" {{action "toggleEditing"}}>{{fa-icon "times" title="cancel"}}</button>
  {{/if}}
{{else}}
  <button class="action-icon" {{action "toggleEditing"}}>{{fa-icon "pencil" title="edit"}}</button>
{{/if}}

...and I can control saving and cancelling in my route, something like this:

in myapp/route/someroute.js:

import Ember from "ember";

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('somemodel', params.model_id);
  },
  actions: {
    save: function () {
      console.log("route: save");
      this.modelFor('somemodel').save();
    },
    cancel: function () {
      console.log("route: cancel");
      this.modelFor('somemodel').rollback();
    },
  }
});

However, I am now confused... what happens if the save fails? How can I plumb it together so that the editing property is set to false only when the save has successfully completed?

Is there some way to access a promise from an action on the route? Am I heading in the right direction with this?




Fetched records in Ember Data are saved in the store even if the call returned 401

When I'm not logged in and go to a route that will fetch a record from my api it will result in status code 401. The error will be handled in the application route and will transition to the login page. When I've logged in the failed transition will be retried.

The problem is that the route will ask the store for the record that is already saved in the store and a new error will be triggered since it doesn't know that I now am authorized to access the record.

Is there any way to tell the store to refetch all records that have received 401?




mercredi 27 mai 2015

How to fix net::ERR_SSL_PROTOCOL_ERROR in Ember REST Adapter

I'm making an EmberJS application on port 4200 using Ember-Cli but it's using a database on port 8080. In my rest adapter, I overwrote find method (just to get something working) like this

find: function(store, type, id){
   return this.ajax('http://localhost:8080/api', 'GET');

}

which is the same as the original find method except that I replace the call to buildURL with a string representation of the host I want to call. Although on the server I explicitly allow cross origin requests, I'm getting a net::ERR_SSL_PROTOCOL_ERROR in the chrome browser. Furtherdown in the error message stack, there's reference to an EMBER.RSVP.Promise.hash.error... In my route, I use Ember.RSVP.hash like this

   model: function(){
         return Ember.RSVP.hash({
           store: this.store.find('mymodelname')
       })

   }

What can I do to make this GET request work?




Hiding query parameters in url using ember

Ember hides the default query parameter, but I would like to keep it hidden in the url whatever the values it takes. Can you do that with ember? If so, could you help me to figure out how?

Thank you




EmberJS Observer Not Firing

EmberJSBin here

I have a component which needs to perform a given operation when any of its values are changed, but the observer I created does not fire:

export default Ember.Component.extend({
    taxes: null,
    NOAYears: 2,
    NOAValues: Ember.computed("NOAYears", function() {
        var NOAs = [],
            lastYear = new Date().getFullYear() - 1;
        for (var year = 0; year < this.get("NOAYears"); year++) {
            NOAs.push({year: lastYear - year, value: 0});
        }
        return NOAs;
    }),
    NOAYearsChanged: function() {
        // does not fire when any of the values change
    }.observes("NOAValues.@each.value")
});

In the component template, I am binding via the {{#each}} iterator:

{{#each NOAValues as |year|}}
    <label for="{{year.year}}-value">{{year.year}}</label>
    {{input min="0" step="any" value=year.value required=true placeholder="Yearly Income"}}
{{/each}}

How can I get my observer to fire when any of the value properties in NOAValues is changed?




Ember transitions in realtime

We use ember 1.8 along with http://ift.tt/1abUfqW to make the transitions on the application look more like other mobile apps ,

However now we need this to work more like the "Tumblr" app where when an item on list is swiped the next view with details will slide over in realtime based on the swiping pattern ,etc that is more you swipe the more of the next view will appear and if you slide on opposite direction you stay on the same page.

Is it possible to do this in Ember or this kind of transition is not possible with our current app?

Please let me know if the question is not worded correctly.

We wanted to be sure this is achieveable in the ember before we try that route.




How to handle errors without URL redirection with Ember

What I'm looking to do is to render custom errors without changing the URL path of the user, so using this.transitionTo is not an option.

So far the following method was working:

v1.10.1 - http://ift.tt/1FaPF5i

But since v1.11.0, there is no way to make it works

v.1.11.3 - http://ift.tt/1J1vvSO

It seems to be 'normal' according to http://ift.tt/1FaPF5k or http://ift.tt/1J1vw92 as the obtained error is:

Error while processing route: stories.index Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined

If I well understood, it is normal, not being able to call render() from the error action now, but what is the good way to do it then?

(I've also posted on github: http://ift.tt/1FaPF5m)

Thank you very much.




Django Rest framework + EmberJS File upload update(patch)

I have a model like this:

// models.py
class MyModel(models.Model):
    name = models.CharField(max_length=30, null=True, blank=True)
    someboolean = models.BooleanField(default=False)
    someotherBoolean = models.BooleanField(default=False)
    myfilefield = models.FileField(upload_to='/files/')

Then i have a serializer like this:

// serializers.py
class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel

Then i have a View which inherit from RetrieveUpdateDestroyAPIView

This Django Rest setup is connected to the EmberJS and is running ok. The data from the server is retrived without any problem and the myfilefield content is represented like a string in ember which is a url to the actual file. When i think of uploading a file to the field on the Django Rest side it seems that i have to play a little with FileUploadParser to make it right and i think this is not much more lines of code into it.

But the issue is that my model on the Ember side should be updated in parts. Sometimes i need to update only the value of someboolean and do not send any files to myfilefield either because the file is already there or because this is done in the other UI iteration (separately). When in Ember i call this.get('model').save(); after some change to the someboolean is made it sends the whole model data back to django rest and the myfilefield in this json request is represented as a string and not as file thus the server returns an error.

As i understand there could be some workarounds to this situation:

  1. The first would be to create custom serializers.CustomFileField which checks whether the provided string is equal to the url which is generated by the serializer on the output and if it is just leaves the file intact.
  2. Second option would be to somehow implement the quick and dirty patch on the ember side which as i understand is still thing under development according to This Link. But this option seems to be quite hard as i have a lot of models with filefields and i should implement the patch method in ember for each and every one of them.
  3. The third option as i forsee would be to create a special File model like so:

    //models.py class File(models.Model): filebody = models.FileField(upload_to='/files/')

and make the myfilefield on the MyModel read_only so it won't validate at any time. I could also implement some method on the File model which would recieve the model and instance for which this file really belongs and after upload and validation would make the myfilefield = filebody This method also seems very dirty but at least keeps some concepts abstracts so i wouldn't need to worry how many models with FileFields i actually have in my project.

My UI expects the user to do the change to one model field at a time and then save the model - i.e. 1. change the name field, save the model.
2. change the boolean field, save the model. 3. upload file, save the model.

Any suggestions on what would be the best way in terms of django rest to accomplish this considering the fact that ember still does not support PATCH requests.




Creating POST Request with non-standard json using Ember-Data

I'm trying to create a post request with Ember Data. In my Giraffe controller, I try to create a record like this.

 var giraffe = this.store.createRecord('giraffe', {
        d: new Date(),
        type: "giraffe"                                        
        });
giraffe.save();

In my models/giraffe.js file, I have this

import DS from 'ember-data';

export default DS.Model.extend({
    d: DS.attr('date'),
    type: DS.attr('string')

});

I am using a key value store for my backend where records are stored according to date. I only need to send a POST request to the backend with the object for the server to store it. Copying some code from Discoruse, in my GiraffeAdapter, I did createRecord like this

  createRecord(store, type, attrs) {
        const data = {}; //copied from discourse
        const typeField = Ember.String.underscore(type); copied from discourse
        console.log(typeField, "typeField");
        data[typeField] = attrs;

        Ember.$.ajax('https://localhost:8080/api/', {  
             type: 'POST',
             dataType: "json",
             data: data,
             success: function(data, response) {
                 console.log(data, response);
             },
             error: function (xhr) {
                 console.log('error')
             }
        });    
    },

this is giving me the following error

Uncaught TypeError: str.replace is not a function

str.replace is used in the Ember.string.underscore method that I copied from discourse and which is defined here

http://ift.tt/1Bp6hWt

var UNDERSCORE_CACHE = new Cache(1000, function(str) {
  return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').
    replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase();
});

In addition to the str.replace error, i'm not sure if I am going about this correctly (i.e. in my attempt to store non-standard json using a POST request).




How to implement a stopwatch countdown using Ember.run.later

The solution boils down to "How to clear interval of Ember.run.later"

  class CountdownTimer {

  constructor() {
    this.counterContinue = false;
  }

  start() {
    this.counterContinue = true;
    this.decreaseCounterLoop();
  }

  stop() {
    this.counterContinue = false;
  }

  decreaseCounterLoop() {
    Ember.run.later(this, function() {
      //do work

      if (this.counterContinue) {
        this.decreaseCounterLoop();
      }
    }, 1000);
  }
}

I tried to implement a countdown timer where I can start and stop at will. But currently this has a bug.

I call stop(), and call start() again quick enough so the decreaseCounterLoop starts looping twice a second.




Ember JS - Unable to loop through an array returned from the model even though it is an array?

I have two Ember JS models (in an Ember CLI application):

  • list
  • link

Each list can have multiple links and as a result, I've declared my list model as:

import DS from 'ember-data';

export default DS.Model.extend({
    title       : DS.attr('string'),
    slug        : DS.attr('string'),
    visibility  : DS.attr('string'),
    owner       : DS.attr('string'),
    links       : DS.hasMany('link')
});

This is what the link model looks like:

import DS from 'ember-data';

export default DS.Model.extend({
    title   : DS.attr('string'),
    shortUrl: DS.attr('string'),
    views   : DS.attr('number'),
    owner   : DS.attr('string')
});

Within the list.js route, I make a call to fetch the list and its links like this:

model: function(params) {
        // Get list properties and links
        var list = this.store.find('list', params.listName);

        return list;
    },

The REST adapter correctly makes the call and my server returns the following response:

{
  "lists": [
    {
      "title": "Design",
      "slug": "design",
      "visibility": "private",
      "owner": "5540b2fb9611f67a07f7f6c1",
      "id": "5565ae05ca217589bc2a1bdf",
      "links": [
        1,
        2,
        3
      ]
    }
  ],
  "links": [
    {
      "id": 1,
      "title": "Dribbble - Show and tell for designers",
      "shortUrl": "http://sl.fi/a1CRgc",
      "views": 144,
      "owner": "5540b2fb9611f67a07f7f6c1"
    },
    {
      "id": 2,
      "title": "Dribbble - Show and tell for designers",
      "shortUrl": "http://sl.fi/a1CRgc",
      "views": 144,
      "owner": "5540b2fb9611f67a07f7f6c1"
    },
    {
      "id": 3,
      "title": "Dribbble - Show and tell for designers",
      "shortUrl": "http://sl.fi/a1CRgc",
      "views": 144,
      "owner": "5540b2fb9611f67a07f7f6c1"
    }
  ]
}

I modeled my response based on the Ember Data Model Maker. I have a list template that should loop through the links in the model so I am doing this:

{{#each links in model}}
    <span>{{ links.title }}</span>
{{/each}}

I get the following error when I load my application and I just can't seem to figure out a solution:

Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed <web-app@model:list::ember388:5565ae05ca217589bc2a1bdf>

Can someone please help me with a solution?




Get request Ember.js on Sails.js

I am creating a web application using Sane stack, which uses Ember.js in the client side as a JavaScript framework, and in th server side it uses Sails.js as a node.js framework.

I use also the Jira API REST to get some data, I can for example GET an Issue via the JIRA API REST with sails.js with a simple controller :

//JiraController
    module.exports = {

            loadProject : function(req, res){

            console.log("Jira contoller");
            var Http = require('machinepack-http');
             process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
             Http.sendHttpRequest({
            url: '/rest/api/2/project/',
            baseUrl: 'http://ift.tt/1PN51s1',
            method: 'get',

            headers: {
              "Authorization": "Basic YWxhYS5lbG90bWFuaTphbGFhNDE0NA=="
            },

            }).exec({

            serverError: function(result) {
            res.send("server error" + JSON.stringify(result));
            },

            success: function(result) {
              res.send("Projects loaded succefly");
            }
            });
            }

    };

In config/routes : I add :

'get /projects' : 'JiraController.loadProject'

I want to get the Issue data in the client side with Ember.js, in other words i want that sails.js request the JIRA API Rest, and then pass the data (JSON) to Ember.js which will display it in a View.

How can I do that please !?




Iframe in Chrome error: Failted to read 'localStorage' from 'Window': Access denied for this document

I have a web app which uses localStorage. Now we want to embed this web app on other sites via iframe. But it does not work. Chrome prints the error message:

Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

I just do the following check:

if (typeof window.localStorage !== 'undefined') {
    // SETUP SESSION, AUHT, LOCALE, SETTINGS ETC
} else {
    // PROVIDE FEEDBACK TO THE USER
}

I checked my security settings in Chrome like described in another Stackoverflow Thread but it doesn't work. Is there any change to make embedding possible without the need of adjusting (default) security settings of most modern browsers?

To give more information, we use Ember-CLI for our web app and turned on CSP (more info about the Ember-CLI CSP). Could CSP cause our web app to throw security errors?




Ember accessing a different controller from a route

I want to access the applicationController from a different route (issue), inside afterModel.

The main goal is to change the background of the application once the promise model is resolved.

This is my issue.js :

import Ember from 'ember';

export default Ember.Route.extend({

  needs: ['application'],
  model: function(params) {
    [... some code ...]
  },
  afterModel: function(model, transition) {
    model.issue.then(function(resolvedIssue) {

      // I'm looking to access the controller here
      var theOtherController = this.get('controllers.application');

      return resolvedIssue;
    });

  }

});

I've tried several combinations, without success. When I try to log stuff in the console, I get a try/catch error message.

What is the proper way to do it?




Ember-data removeObject on a hasMany relationship also removes the child entry from Ember's Store

I have two models:

App.User = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    phoneNumber: DS.attr('string'),
    studies: DS.hasMany('study', {async: true})
});

App.Study = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
});

I want to un-assign some Studies from a User.
When the user presses the un-assign button in the view, there is an action inside the controller which runs this code:

actions: {
 //...
 unassign: function(study){
     this.get('user').get('studies').removeObject(study);
     this.get('user').save();
 }
 //...
}

This removes the studyId from the users.studies list, but it also removes that study completely from Ember's store.

How can I just un-assign the study from the user.studies , but keep the studies table unaffected.

I'm using:

Ember VERSION = '1.5.1';
Ember-Data Version = 1.0.0-beta.6




How to set default values for query params based on dynamic segment?

I am creating universal grid for some entities. For that I added this in routes:

this.route('record', { path: '/record' },function() {
   this.route('index', {path: '/:entity'});
   this.route('view', {path: '/:entity/:record_id'});
});

and created new "index" route:

export default Ember.Route.extend({
  entity: '',

  queryParams: {
    sort: {
      refreshModel: true
    }
  },

  beforeModel: function(transition) {
    var entity = transition.params[this.get('routeName')].entity;

    this.set('entity', entity);
  },

  model: function(params) {
    delete params.entity;

    return this.store.findQuery(this.get('entity'), params);
  },
}

my controller

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

  sort: ''
}

how can I set default value for the "sort" based on dynamic segment? For example in my settings I store sort values for all entites:

'settings.user.sort': 'email ASC',
'settings.company.sort': 'name ASC',

I tried to define "sort" as computed property, but its "get" method is called in time when I can't get a value of dynamic segment from currentHadlerInfo or from route.

Also defining of the property "sort" as computed property has strange effect, for example, when I define it as

sort: 'email ASC'

in my template it is displayed via {{sort}} as expected (email ASC). but when I return a value from computed property, I see empty value in my template and this affects on a work of components (I can't get current sorted column)

What can I do?..




Ember-data - Sails - lazy fetch of hasMany relationship at a specific url, without payload links or ids

Using the classical models:

app/models/post.js
export default DS.Model.extend({
  comments: DS.hasMany('comment', {async: true})
});

app/models/comment.js
export default DS.Model.extend({
  post: DS.belongsTo('post', {async: true})
});

If I ask my sails API for

/posts/

will return this payload:

[
  {
    "id": 1
  },
  {
    "id": 3
  }
]
// those are posts

No sideloading of comments, not even a link. This is as intended. What my API has is a specific url to load a post's related comments (generated by the standard sails blueprints):

/posts/1/comment/

[
  {
    "post": 1,
    "id": 1,
  },
  {
    "post": 1,
    "id": 2
  },
  {
    "post": 1,
    "id": 3
  }
]
// those are comments

When I access a post's related comments through the hasMany relationship, typically in a template like this:

<ul>
  {{#each comment in post.comments}}
    <li>My comment id: {{comment.id}}!</li>
  {{/each}}
</ul>

I would like ember to load my currently-not-fetched related comments at the specified url. There are 2 not really documented methods on the RestAdapter that I though I could override for this: findHasMany and/or urlForFindHasMany, but those functions are never called by ember-data. I assume they need a link to be provided by the API. I have hacked my object controllers to fetch the data anyway, but I feel dirty doing this and I'd rather move the logic to the adapter.

Is there a way to achieve lazy loading of hasMany relations through a url of the following form?

/parentModel/:id/relatedModel/




Ember Data - How to observe for parent model change from child model

I want to observe for changes in a isParentValid-property of parent's model, and update the isChildValid-property of child model base on that.

I want to do something like below.

Parent Model

export default DS.Model.extend({
    child: DS.hasMany('child', { inverse: null }),
    isParentValid: DS.attr('boolean', {defaultValue: false})
});

child Model

export default DS.Model.extend({
    isChildValid: Ember.computed('parent.isParentValid', {
    get: function () {
        //return true if isParentValid property is true
        //else return false
     })
});

Tried few ways not able to figure it out. I am not even sure that if it is even possible




mardi 26 mai 2015

Could not find the "presence" validator with Ember Validations addon

I'm trying to use the Ember Validations addon and I can't get it working. In the Chrome console, I see: WARNING: Could not find the "presence" validator.

Here is my model:

import Ember from 'ember';
import DS from 'ember-data';
import EmberValidations from 'ember-validations';

export default DS.Model.extend(EmberValidations.Mixin, {
  name: DS.attr('string'),

  validations: {
    name: {
      presence: true
    }
  }
});

And here is the my test:

test('isValid is false if name is not set', function(assert) {
  stop();
  var model = this.subject();
  Ember.run(function() {
    model.validate().then(function() {
      assert.equal(model.get('isValid'), false);
      start();
    });
  });
});

The result of this test is "expected false but got true". Thanks in advance!




Structuring ember data without making an additional model

I'm building an app where users can take todos. When they take tasks, I want to save them as "helpers" under the todo model.

Is there a way to do this without creating a separate model for helpers? It would be ideal to save helpers as user.helper.

I don't want to just save users as users under the todo model, because I already save the todo creator in todo.user.

Thanks!

Todo.js:

countMe: function(id) {

            var user = this.controllerFor('application').get('model');

            var todo = this.store.createRecord('todo', {
                helper: user,
            });

            this.store.find('todo', id).then(function(todo) {
                helper.get('todos').addObject(todo);
                helper.save();
            });

        },

Todo.js - model:

export default DS.Model.extend({
    title: DS.attr('string'),
    isCompleted: DS.attr('boolean', {defaultValue: false}),

    list: DS.belongsTo('list', {async: true}),
    user: DS.belongsTo('user', {async: true}),

    comment: DS.hasMany('comment', {async: true}),
    helper: DS.hasMany('helper', {async: true}),
});

User.js:

export default DS.Model.extend({
    displayName: DS.attr('string'),
    email: DS.attr('string'),

    list: DS.hasMany('list', {async: true}),
    todo: DS.hasMany('todo', {async: true}),
    comment: DS.hasMany('comment', {async: true})
});




Can't find whats wrong. JavaScript, PouchDB, HTML to array

I have a form, that is being filled, and fields are added to DB. After that DB is displayed in the browser in a table. User has to check the rows that he needs to add to txt file to later send.

So far I got stuck on transfering table data into an array, to later check the checkbox and to either add to text file or not.

<!DOCTYPE html>
    <html>
    <head>
        <title>Vaucher Entry</title>
        <link type="text/css" rel="stylesheet" href="css/normalize.css" />
        <link type="text/css" rel="stylesheet" href="css/style.css" />

        <script type="text/javascript" src="js/date.js"></script>
        <script type="text/javascript" src="js/jquery-1.11.3.js"></script>
        <script src="http://ift.tt/1FzPymq"></script>
        <script src="http://ift.tt/1FzPyms"></script>
        <script type="text/javascript" src="js/handlebars-v3.0.3.js"></script>
        <script src="http://ift.tt/1akd9df"></script>
        <script src="http://ift.tt/1e1uqGJ"></script>
        <script type="text/javascript" src="js/pouchdb-3.5.0.min.js"></script> 
        <script type="text/javascript" src="js/app.js"></script>
        <script type="text/javascript" src="js/db.js"></script> 
    </head> 


    <body>
      <script type='text/x-handlebars' data-template-name='application'>
      <h2>Model Irrigation Voucher Entry</h2>

            <div id="leftColumn">
                <ul>
                    <li><a href="#" onclick="vaucherEntry(); return false; showVauchers()">Vaucher Entry</a></li>
                    <li><a href="#" onclick="settings(); return false;">Settings</a></li>
                    <li><a href="#" onclick="about(); return false;">About</a></li>
                </ul>
            </div>

        <div id='container'>
            <div id="form" action="#" method="post">
            <form name='VaucherForm' >
                <legend>Vaucher Entry</legend>
                <div id="both">
                    <div id="left">
                        <label for='vaucherID'>Vaucher ID:</label><input type="text" maxlength="8" name="vaucherID" id="vaucherID"><br>
                        <label for="vendorID">Vendor ID:</label><input type="text" maxlength="10" name="vendorID" id= "vendorID"><br>
                        <label for="amount">Amount:</label><input type="number" maxlength="17" name="amount" id="amount"><br>
                    </div>  

                    <div id="right">
                        <label for="date">Date:</label><input type="date" maxlength="10" name="date" id="date"><br>
                        <label for="invoiceNumber">Invoice #:</label><input type="number" maxlength="28" name="invoiceNumber" id="invoiceNumber"><br>

                        <div>   
                            <div id="fundDiv"><label for="fund">Fund:</label><input type="text" maxlength="5" name="fund" id="fund" value="I30"><br></div>
                            <div id= "deptDiv"><label for="deptID">Dept. ID:</label><input type="text" maxlength="7" name="deptID" id="deptID" value="18I"><br></div>
                        </div>  
                    </div>
                </div>

                <div>
                    <label for="descript">Description:</label><input type="text" maxlength="30" name="descript" id="descript" onkeydown="if (event.keyCode == 13) {addVaucher()}">
                    <!--//<label for="mysteryNumber">Mystery #:</label><input type="text" maxlength="30" name="mysteryNumber" id="mysteryNumber" value='3700'>-->
                </div>

                <button type="button" onClick="addVaucher()">Add Vaucher</button>
                <button type="reset">Clear Form</button>
            </form>
        </div>

          <div id='table'></div>
        </div>

        <footer class='container'>
          <hr />
          <p class='pull-left'>&copy; 2015 
        </footer>
      </script> 

    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript" src="js/htmlToText.js"></script> 


    </body>
    </html>

This is the htmlToText.js

var details = $('#tableData tbody tr').map(function (i, row) {
    return {
  'number': row.cells[0].textContent,
        'vendorID': row.cells[1].textContent,
        'amount': row.cells[2].textContent,
        'date': row.cells[3].textContent,
        'invoiceNum': row.cells[4].textContent,
        'fund': row.cells[5].textContent,
        'deptID': row.cells[6].textContent,
        'description': row.cells[7].textContent,
        'checkBox': row.cells[8].textContent
    }
}).get();
console.log(details);

So far it returns an empty array. Thou if I try the simplified version of just having a simple html file with the table, htmlToText.js works like a charm.

Can it be because of me using ember.js in my html file?




Why Array controller with itemcontroller has different 'this' object?

I defined an arraycontroller as:

Kiford.ChatboxesController = Ember.ArrayController.extend({
itemController: 'chatbox',
currentParticipant: undefined,
actions:{
    react: function(){
       console.log(this);
    },
}

and I have a template using this controller:

{{#each item in controller}}
    <div {{action 'react'}}>test react</div>
{{/each}}

when I clicked on the div with 'test react' text, the output of console prints value of this:

enter image description here

But when I send action from another controller as:

this.get('controllers.chatboxes').send('react');

The output value of 'this' is:

enter image description here

Apparently, the two 'this' are completely different objects, Why?

and How I can access the first 'this' object with child controller object when I send action from other controller?




Test cases for Helper in ember-cli application

I have created helper file in ember for formatting date using moment.js library. Helper has some if else conditions. When I generated this helper using ember-cli command, a test file also created. But i couldnt write test case inside it. When i run the test, it shows error that wbFormatDate (my helper name) is not a function. Have anybody faced this issue before? Please let me know the best practive to create test cases for helper in ember-cli application




Sort Ember Array on first load only

I have a form with numerous children which I would like to sort alphabetically.

For this I've used an Array Proxy and the SortableMixin on a computed property, the issue I'm experiencing is when a new item is added to the obeserved property the collection sorts itself again.

What I would like to happen is to have the collection sorted on the first load, and then after that not be sorted.

Here's a jsbin example of the current setup, if you click add a new item will be added to the collection, as soon as you start typing in the new item's input the collection will re-sort which is not ideal.

http://ift.tt/1LFboHw




Ember Controller Property, Promise, and Scope

Very new to Javascript and even newer to Ember here, I have an async hasMany association and I'm trying to sum a property on the child model (tournament) in the parent models controller. My understanding of function scope is that the inner functions will have access to everything in the containing functions (except for this), and that's been fine till now. I'm trying to add to amount when the promise resolves, but it must be making a new amount variable because as soon as I make it back to the outter forEach it's back to 0, and I'm not sure where I'm going wrong. I'm aware I'm not setting the dependencies in the .property(), I just wanted to sort this out first.

totalPrice: function(){
    var self = this;
    var allTourn = this.get('model.tournaments');
    var amount = 0;

    allTourn.forEach(function(tournament){
        var tID = Number(tournament.get('id'));

        self.store.find('tournament', tID).then(function(value){
            amount += Number(value.get('buyIn'));
            //amount is set to the buyIn property as expected
        })

        // amount is 0 out here... shouldnt the amount in the promise be using the outter amount variable?
    });

    return amount; // == 0
}.property()




Ember: Properly using store within component

Relevant info: Ember 1.11.1 Ember Data 1.0.0-beta.16 Ember CLI

I am attempting to make a reusable component for metrics within my application. From within the component, it runs the query with the selected options. The problem is, even though I see the network request kick off properly, it is never getting entered into the Ember object.

Here is my component code:

import Ember from 'ember';

var arr = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);

export default Ember.Component.extend({
store: Ember.inject.service(),
type: null,
startTime: null,
finishTime: null,
interval: 0,
detail: false,

didInsertElement: function() {
    // Ensure we have the latest metric types
    this.set('metricTypes', arr.create({
        promise: this.get('store').find('metric-type')
    }));
},

data: function() {
    var results = this.metricQuery();
    return results;
}.property(),


/* NOT PROPERTIES */

metricQuery: function() {
    return this.get('store')
               .find('metric-query', { type: this.get('type'),
                                       startTime: this.get('startTime'),
                                       finishTime: this.get('finishTime'),
                                       interval: this.get('interval'),
                                       detail: this.get('detail') });
}
});

I am seeing the metricTypes return and get set to an Ember object correctly. But when the metricQuery function runs, the object does not get set. I see the property in the inspector, but there is no content. I do however see the network request go out correctly with the correct data, and sideloaded data, returned:

{"metricQuery":{
    "id":"00000000-0000-0000-0000-000000000000",
    "metricType":["c47707e1-a9d1-420a-87b6-4e65b77e6a58"],
    "metricResult":"1035be30-cf6e-4425-ac58-d0e2fd2cf7b1"},

"metricResult":{... data... }

"metricType":[{.... data....}]}

But when I look at the object in the Ember inspector, I see empty content. This is the first time I've tried to use the store to fetch data from within a component, and I'm not sure what I'm doing wrong.

How can I access the data that is being returned from the find on metricQuery?

Thanks in advance for any help.




How to Transition to (the current) route

In my app I'm able to select a " group" model from anywhere in the app. All groups are loaded into the application's model hook, and then the selectedGroup is saved as a property in the application controller.

A lot of the routes have models that are dependent on the selectedGroup, so when a new group is chosen, I need to reload the current route. From what I've been able to read, the best way to achieve this is to just to transitionToRoute.

Is this the best way to do things? And how do I get the current route, in order to then re - transition to it.

Please comment if further explanation needed! Thanks!




container.lookup deprecation alternative?

Ever since ember 1.12 i get a deprecation notice for this line of code. Which sits in a component not an initializer.

this.container.lookup('application:main');

Notice:

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

What other way is there to get a hold of the main application container?




How do you import a newly created ember addon?

I'm trying to create my first Ember AddOn and I'm getting stuck importing it into an Ember project. I've created the addon and published to github like this:

ember-cli$ ember addon test-addon
ember-cli$ cd test-addon
ember-cli/test-addon$ git remote add origin <github-url>

Then, from my project, I've tried to import the addon:

# app/rotues/index.coffee
import TestAddon from 'test-addon'

But, I'm getting this error on the console:

Uncaught Error: Could not find module `test-addon` imported from `test-app/routes/index`

Any ideas where I'm going wrong? I can see the addon in the node_modules directory but not in bower_components. I think(tm) this is my issue but I'm not sure what else I need to do to setup my addon.




Can't attach jQuery Plugins that is inside {{#if}} in EmberJS

In my emberjs app. I have bunch of jquery plugins that I need to bind to various elements.

I am using this piece of code to initiate jquery plugins for elements.

App.ApplicationView = Ember.View.extend({
    didInsertElement: function(){
        window.appPluginsInit(); // all jquery plugin init

        // chart client init
        var chartClientSettings = {
            serverUrl: config.ajaxUrl
        };

        this.$('.chart-client').chartClient(chartClientSettings);
    }
});

This only works for element that are initially loaded to the page. But for example if an element is under {{#if}} it doesn't seem to be attached with plugins.

Works

<button class="chart-client">Show Chart</button>

Doesn't work

Considering the someVar is false on initial load.

{{#if someVar}}
<button class="chart-client">Show Chart</button>
{{/if}}




Ember CLI -- How can I get variables to survive page refreshes?

I'm setting a variable on my application controller and calling it from other controllers.

export default Ember.Controller.extend({
  needs: ['application'],
  foo: Ember.computed.alias('controllers.application.foo'),
});

This works great for keeping information when re-routing, but the only problem is that it does not survive a manual refresh of the page. So how do I make it so that it does? I only found one other question about this here but it does not have an answer.




Model object not preserved when using hash for model in ember route

Been trying to resolve this for a while now and I'm clearly not understanding how the relationship between model and setupController works. I have a model which is returning a hash; the result of two find calls:

model(params) {
  return Ember.RSVP.hash({
    course: this.store.find('course', params.course_id),
    topics: this.store.find('topic', { course_id: params.course_id })
  });
},

The first time setupController gets called, the value of model if as expected, a hash like { course: Class, topics: Class }. Awesome, that's what I want.

However, the next time setupController gets called (for example, transition to another route and then press the back button in the browser), the model is now just the course Class:

setupController(controller, model) {
    // when first called model will be { course: Class, topics: Class }
    // next time entered, model will just be Class (just the value of "course" )
    // why is the model object not preserved?
   controller.set('model', model.course);
   controller.set('topics', model.topics);
}}

If I just make model() return a single resource, it's the same every time:

model(params) { return this.store.find('course', params.course_id); }
// now `model` will always be "course" in setupController

Why is the original model not preserved when using a hash result? Am I doing something wrong?




Confusion About Observers and Unconsumed Computed Properties

I am having trouble understanding the statement below and have read it multiple times unfortunately:

If you never get a computed property, its observers will not fire even if its dependent keys change. You can think of the value changing from one unknown value to another.

This doesn't usually affect application code because computed properties are almost always observed at the same time as they are fetched. For example, you get the value of a computed property, put it in DOM (or draw it with D3), and then observe it so you can update the DOM once the property changes.

This is part of

http://ift.tt/1dveqUd

An example of an observer is:

Person = Ember.Object.extend({
  init: function() {
    this.set('salutation', "Mr/Ms");
  },

  salutationDidChange: function() {
    // some side effect of salutation changing
  }.observes('salutation').on('init')
});

Does this mean that if I don't call

person.get('salutationDidChange') it will be considered an unconsumed computed property, and it will not execute even if salutation changes?




Ember-cli get relative path of a dependency

I have a unique issue that I can't get out because of how ember works with the dependencies. I am using this lib to check a phone number : http://ift.tt/1dv3iXk

And it's working fine, until that I have to set the relative path of a file call util.js like this to make some options works:

 $phoneInput.intlTelInput({
                    allowExtensions: false,
                    autoFormat: true,
                    autoHideDialCode: false,
                    nationalMode: false,
                    utilsScript: "/bower_components/intl-tel-input/lib/libphonenumber/build/utils.js"
                });

As you can see I tried to use /bower_components/intl-tel-input/lib/libphonenumber/build/utils.js but it can't find it. I also tried to add assets/ or ../bower_... but nothing is working, and I'm afraid this is not possible.

I did import the file in my Brocfile.js :

app.import('bower_components/intl-tel-input/lib/libphonenumber/build/utils.js');

And I can see it perfectly in the source.

Is there is a way to know the relative path of a dependency ?

I forgot to precise that I am initializing intlTelInput from a view within didInsertElement.

Thanks.




Cannot get value of ember select object from component

I'm new to Ember, so another Ember question - I have a template which contains a form. The form contains two select objects and a submit button. The select objects are components. What I'm having trouble with is getting the selected value of the select objects when the submit button is clicked. Here is the template code for one of the select objects:

{{
  view
  content=relationshipTypes
  value=selectedRelationshipType
  selection=selectedRelationshipType
  prompt="Select Relationship Type..."
}}

Here is the component.js code for the select object:

export default Ember.Component.extend({
  classNames: 'btn-group relationship-type-select'.w(),
  change: function(event) {
    var typeSelected = this.get('selectedRelationshipType');
    this.set('selectedRelationshipType', typeSelected);
  }
});

And in the route.js for the template that contains the submit button (with an action for createRelationship):

export default Ember.Route.extend({
  model: function() {
    return this.modelFor('people.show').get('entityRelationships');
  },
  setupController(controller) {
    this._super.apply(this, arguments);
    controller.set('person', this.modelFor('people.show'));
  },
  actions: {
    relationshipEntityTypeSelected: function(type) {
      console.log("IN RELATIONSHIPENTITYTYPESELECTED.TYPE");
      this.set('selectedRelationshipType');
    },
    createRelationship: function() {
      var fromEmfId = this.modelFor('people.show').id
      console.log("FROM EMF ID==>" + fromEmfId);
      var toEmfId = "";
      var relationshipType = this.get('selectedRelationshipType');
      console.log("RELATIONSHIP-TYPE==>" + relationshipType);
    }
  }
});

So all I want is to be able to get the selected relationship type in the createRelationship function, but I have been unable to do it so far. If anyone can tell me what I'm doing wrong, I would appreciate it. Thanks.




Set controller property to first model

I want to set a controller property to the first object of the models but can't get the syntax right.

My application route...

model: function(){
    return this.store.find('group');
}

And then in my application controller, I'm trying something like...

activeGroup: function(){
        return this.get('model.firstObject');
    },

I've got a function a little later to set activeGroup to whichever is chosen, but I want it to be set as the first (or any) class by default.

Thanks!




Display global/misc error message to user

I'm trying to display error messages for the user in Ember. Is there a way to do this from Logger? I've read about the error substate, but I think that only displays when there's an error in a transition. Is there a way for me to set a property in the ApplicationController to the error message object (and thus display it in a template)? If there's an error in an AJAX call, or a bug, or some other issue, I want the user to be notified that something is awry.

The Coffeescript:

 Ember.Logger.error = (message, cause, stack) ->
  console.error(message, cause, stack) #show in console
  Raygun.send(new Error(message), null, { cause: cause, stack: stack }) #log error on server

  # how do I display the error message to user?, THIS DOESN'T WORK b/c "this" is undefined:
  @container.lookup('controller:main').set('errorObjetct', message)

I'm using Ember 1.11.1 in ember-cli.

Anyone have any tips on this?

Bryan




Emberjs components actions

I am trying to use Emberjs components. And I stumbled into trouble with actions.

Here my component:

export default Ember.Component.extend({

    actions: {
        openObject: function (id) {
            this.sendAction('openObject', id);
        }
    },
...

And here my controller, also I have created the same action in the route.

export default Ember.Controller.extend(
    {
        actions: {
            openObject: function (id) {
                    self.transitionToRoute('objects.bc', id);
            }
        }
    }
);

And what I need is just to make transition by action from component.

And it is work only if I connect controller action and component action this way:

{{bc-table openObject="openObject"}}

Is there some way to send action from component to router/controller without such connection?




EmberJS: Test a Serializer with Store involved using ember-mocha

I am rewriting my yeoman ember project to use ember-cli, and am now stuck on rewriting my serializer test, as Mocha's describeModel function brings in a store ...

import { expect, assert } from 'chai';
import { describeModel,it } from 'ember-mocha';

describeModel('connection','Connection Desc', { needs: ['model:result'] },
  function() {
    it('exists', function() {
      var model = this.subject();
      var store = this.store();
      expect(model).to.be.ok;
    });
});

... but describeModule does not. As a work-around I am manually create a store, but guess that's is not very convinient and am sure there is a more readable way to do so:

import App from '../../../app';
import { expect, assert } from 'chai';
import { describeModule, it } from 'ember-mocha';

describeModule( 'serializer:result', 'Result Serializer', { needs: ['model:result'] },

function() {

  it('convert a single item on a result to a one element array', function(){
    var serializer = this.subject();

    App.ApplicationStore = DS.Store.extend({
      adapter: DS.MochaAdapter
    });
    var store = App.ApplicationStore.create({
      container: this.container
    });

    expect(
      serializer.extractArray( store, store.modelFor('result'), {"results":[]})
    ).to.be.an.instanceOf(Array).and.have.lengthOf(0);
  });
});

There exists the possibility to mock, but mocking every single possible method of the store does not sound tempting.

Is there a shorter way of getting the DS.Store instance (similar to the subject) for the example above?




Any way I can load KML data from Google maps (again) via JS API?

I’ve been working on a little ember app for a while which loaded articles from a local newspapers API and presented it in a nice layout. As these articles are all about travel destinations, the navigation is based upon a big map with markers in the background of the page. Originally I started out with a leaflet map. Adding a marker for each article was no problem, as I knew their coordinates as they were saved with each article and accessable through the API.

It got more complicated when I realized that some authors embedded small Goolge maps into their copy with markers for nice sites, bars, etc. As I didn’t want to have a Google map displayed over a leaflet map, I was searching for way to get the marker data from the Google maps and use it on my Leaflet one. The solution I ended up working with was pretty crazy but did what I was hoping for: I realized that an HTTP request to a Google map’s embed url with the request parameter “output” set to “kml” got me an KML/XML file with all the data of the KML layer used with the map. To circumvent issues with cross-domain requests I requested the KML data indirectly through Yahoo’s YQL service which kindly converted the data to JSON as well.

Everything was fine. Until it wasn’t. Since implementing the recent changes to the API (especially regarding KML stuff), my requests return KMZ (zipped KML) data. Of course neither YQL conversion nor my Ember app can deal with the now binary data.

It doesn’t seem there is any way to get my hands on the uncompressed data again. Is there at least a way to make my main map–which is now a Google map, too–load the kml layer from another map identified by an embed url? Any hint is welcome and really appreciated. Thanks!