jeudi 31 mars 2016

Getting Errno::ENOENT: No such file or directory - chdir when running rake ember:install

I want rails to serve my ember front, and I'm using: ember-cli-rails

I set my config/initializers/ember.rb as:

EmberCli.configure do |c|
  c.app :item_tracking
  c.app :frontend, path: "~/myApp/client/dist"
end

and config/routes.rb as:

Rails.application.routes.draw do
  mount_ember_app :frontend, to: "/"
end

When I run rake ember:install, I got:

Errno::ENOENT: No such file or directory - chdir

I'm sure I build the entire ember in ~/myApp/client/dist, and I guess the problem is caused by this path, can someone give me a suggestion?




Ember Loading Template never displaying

I have tried

/app/routes/loading.hbs
/app/pods/loading/template.hbs
/app/pods/loading.hbs
/app/pods/application/loading/template.hbs
/app/pods/application/loading.hbs
/app/templates/loading.hbs
/app/templates/application-loading.hbs

None of the above ever work.

I added this to my application route and it works, but it is only rendering the spinner in the application template not the outlet not the appropriate outlet of the current route.

  //app/pods/application/template.hbs
  {{#if isLoading}}
      <i class="fa fa-spinner fa-pulse fa-5x"></i>
  {{/if}}

  //app/pods/application/roue.js
  actions: {
    loading(transition, originRoute) {
      let controller = this.controllerFor('application');
      controller.set('isLoading', true);
      transition.promise.finally(function() {
        controller.set('isLoading', false);
      });
    }
  }

What amy I doing wrong? Why are the templates not rendering? I am using ember-cli@2.4.2 with ember@2.4.1




Ember.js Google maps warning persists even though I reverted to previous commit

Following this old deprecated guide, but I realized it was deprecated and reverted to a previous commit, thinking, OK, let's start clean here.

Problem is, even on this old commit, I am seeing this warning:

Google Maps API warning: NoApiKeys http://ift.tt/1Lj5JMz

/Jackie Chan wwwwww




Using precompiled Handlebars templates in Ember 2 project

I'm need to use some precompiled handlebars templates in my ember project along with my normal components and templates. I've loaded the precompiled templates in my ember-cli-build.js file using app.import(). The precompiled templates are now showing up in the Handlebars.templates object, which I mapped to Ember.TEMPLATES["precompiled-template"] in my Ember app.js file between the app declaration and app initialization.

When I check the Ember.TEMPLATES object, the precompiled templates are there as functions of the form function(context, options) unlike the other templates which are objects.

When I try to use the precompiled template nothing shows up. Any thoughts?




ember data relationships and ready/loaded event

Until ember data has built-in dirty relationship tracking, we have rolled our own. After upgrading to Ember/Ember Data 2.4.3 (from something quite old), our custom solution stopped working.

The problem comes down to knowing when to make a snapshot of a record's relationship state as the "original" state against which we can compare later states.

Let's say an adapter's payload includes the following:

{
    id: 'post-1',
    type: 'post',
    relationships: {
        comments: {
            data: [{ type: 'comment', id: 'comment-1' }]
        }
    }
}

In the ready hook for the resulting record, and using the new references API, I'd expect to be able to say something like:

ready: function() {
    var commentIds = this.hasMany('comments').ids();
    // would expect commentIds to be ['comment-1']
}

But this seems not to work -- commentIds is an empty array.

(Note that observing the isLoaded property also doesn't seem to give me what I want—the record is already in the loaded state when the ready event fires.)

Basically I'd like to have something like a relationshipsLoaded event which is fired when a record's relationships have been populated with respect to an adapter's payload. The related records themselves may not be available or loaded, but that shouldn't impact the record's state of having a relationship, based on the data returned from an adapter.

After some spelunking I've found that hooking into the store's backburner will provide something that seems to work:

ready: function() {
    this.store._backburner.schedule('finished', this, function() {
        var commentIds = this.hasMany('comments').ids();
        // commentIds is now ['comment-1']
    });
}

But this is obviously sketchy and I'm not sure that it's really guaranteeing what I'd like it to be guaranteeing.

So: is there a real way to do this? A better way? Is this a feature that is forthcoming?

For reference I made a codepen illustration: http://ift.tt/1RNr0gQ




Loading handlebars templates and helpers alongside ember templates/components

I'm having to load in a library of Handlebars templates (and their associated helpers) to use in my ember project.

Initially I was hoping I could make the templates into components with some app.import(url, {destDir:"foo/"}) but I haven't found a nice way to change the filenames of my handlebars templates (we are using the pod structure so ember expects the .hbs files to be named template.hbs). I need a way to do this programmatically because the handlebars templates may be updated and I need those updates to be reflected in my app.

Another issue I'm running into is the templates are written using the {{{bar}}} syntax that Ember's HTMLBars doesn't like.

I've been thinking about namespacing the handlebars components are loading them up on the initial load but I'm not sure how to do that in a way the ember recognizes the handlebars templates.




Ember datetime in the url

I have a controller with property:

vFrom: window.moment.utc().format('YYYY-MM-DD'),

I'm using this property in a route inside queryParams of ember-cli-pagination

vFrom:{
  refreshModel: true
},

I can change this date via a ember-pikaday, I set the init date in the controller vFrom: window.moment.utc().format('YYYY-MM-DD') and then use it in datepicker component:

{{pikaday-input useUTC=true value=vFrom class="form-control"}}

Which then triggers model refresh on date change (which is what I want).

The problem is that I end up with a date variable in the URL ?vFrom=Fri Mar 25 2016 01%3A00%3A00 GMT%2B0100 (CET) which is not working in all browsers (and moment warns me about this in the console) and ends up breaking my app.

How can I change the date format that ends up in the URL?

Thank you!




Bower Tunnelling error in corporate proxy

I am trying to setup new Ember application using ember-cli but getting this error even after updating proxies in "C:...\bower\node_modules\bower-config\lib\util\defaults.js"

Installed packages for tooling via npm. Error creating new application. Removing generated directory ./ember-quickstart Request to http://ift.tt/1TkEqTN failed: tunnelin g socket could not be established, cause=write EPROTO 101057795:error:140770FC:S SL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:794:

Error: Request to http://ift.tt/1TkEqTN failed: t unneling socket could not be established, cause=write EPROTO 101057795:error:140 770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt. c:794:

at createError (C:\Users\user\AppData\Roaming\npm\node_modules\ember-cli\no de_modules\bower\lib\node_modules\bower-registry-client\lib\util\createError.js: 2:15) at Request._callback (C:\Users\user\AppData\Roaming\npm\node_modules\ember- cli\node_modules\bower\lib\node_modules\bower-registry-client\lib\lookup.js:97:2 9) at self.callback (C:\Users\user\AppData\Roaming\npm\node_modules\ember-cli\ node_modules\bower\lib\node_modules\request\request.js:198:22) at emitOne (events.js:77:13) at Request.emit (events.js:169:7) at Request.request.emit (C:\Users\user\AppData\Roaming\npm\node_modules\emb er-cli\node_modules\bower\lib\node_modules\request-replay\index.js:89:29) at Request.onRequestError (C:\Users\user\AppData\Roaming\npm\node_modules\e mber-cli\node_modules\bower\lib\node_modules\request\request.js:820:8) at emitOne (events.js:77:13) at ClientRequest.emit (events.js:169:7) at ClientRequest.onError (C:\Users\user\AppData\Roaming\npm\node_modules\em ber-cli\node_modules\bower\lib\node_modules\tunnel-agent\index.js:178:21)

Thanks in advance.




tinymce get html content and place it as email body using ember.js

I'm using tinymce editor for sending an email.While sending actual email in mscrm activities and ember.js framework ,Email body is sent as HTML source not as actual HTML format. E.g while receiving an email I got format as '<'strong'>test<'/strong'>'

not as 'test' in bold.Please suggest.

below is the init function i have used

RichTextArea = Ember.TextArea.extend({
editor: null, _suspendValueChange: false, didInsertElement: function () { debugger; var id = "#" + this.get("elementId"); var view = this; tinyMCE.init({ width: "700", height: "400", plugins : "table,inlinepopups",

        // Style formats
        style_formats : [
                {title : 'Bold text', inline : 'b'},
                {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
                {title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
                {title : 'Example 1', inline : 'span', classes : 'example1'},
                {title : 'Example 2', inline : 'span', classes : 'example2'},
                {title : 'Table styles'},
                {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
        ],

        formats : {
            alignleft : {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'left'},
            aligncenter : {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'center'},
            alignright : {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'right'},
            alignfull : {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'full'},
            bold : {inline : 'span', 'classes' : 'bold'},
            italic : {inline : 'span', 'classes' : 'italic'},
            underline : {inline : 'span', 'classes' : 'underline', exact : true},
            strikethrough : {inline : 'del'},
            customformat : {inline : 'span', styles : {color : '#00ff00', fontSize : '20px'}, attributes : {title : 'My custom format'}}
        },
        mode: "specific_textareas",
                    editor_selector : "mceEditor",
                    theme: "advanced",
                    theme_advanced_resizing: true,
        //// Theme options
        //            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,|,table,removeformat,code",
        //            theme_advanced_buttons2: "",
        //            theme_advanced_buttons3: "",
        //            theme_advanced_buttons4: "",
        //            theme_advanced_toolbar_location: "top",
        //            theme_advanced_toolbar_align: "left",
        //            theme_advanced_statusbar_location: "bottom",
        //            theme_advanced_resizing: true,
                   theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
                    theme_advanced_toolbar_location: "top",
        selector: id,
        element_format : 'html',
        setup : function(ed) {
            view.set("editor", ed);
            ed.onKeyUp.add(function (ed, e) {
                view.suspendValueChange(function () {
                    view.set("value", ed.getContent());
                });
            });
        },
        valid_styles: {
            '*': 'border,font-size',
            'div': 'width,height'
        }
    });
},
suspendValueChange: function(cb) {
    this._suspendValueChange = true;
    cb();
    this._suspendValueChange = false;
},
valueChanged: function() {
    if (this._suspendValueChange) { return; }
    var content = this.get("value");
    this.get("editor").setContent(content);
}.observes("value"),
willClearRender: function() {
    this.get("editor").remove();
}

});




Error while processing route: index Assertion Failed: You must include an 'id'

I'm making an End-of-degree project of a city dashboard. I'm usin: - PostgreSQL as DB - Node.js + Express.js + Massive.js as server - Ember.js as client app

Actually, I'm testing if I can get the data from DB to Ember, but I'm getting the next error (I've tried almost every solution I found here):

Error while processing route: index Assertion Failed: You must include an 'id' for poblacio in an object passed to 'push' Error: Assertion Failed: You must include an 'id' for poblacio in an object passed to 'push'

These are my files:

server.js (just a piece)

router.route('/poblacios')
        .get(function(request, response) {
            db.poblacio.find({}, function(err, res){
                response.json(res);
            });
        });

 app.use('/api/v1/', router);

adapters/application.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    namespace: 'api/v1'
});

route/application.js

import Ember from 'ember';

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

models/poblacio.js

import DS from 'ember-data';

export default DS.Model.extend({
  anny: DS.attr('number'),
  districte: DS.attr('number'),
  barri: DS.attr('string')
});

serializers/poblacio.js

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
    primaryKey: 'id',
    normalizeFindAllResponse(store, type, payload) {
        return {
            data: {
                id: payload.id,
                type: type.modelName,
                attributes: {
                    anny: payload.anny,
                    districte: payload.districte,
                    barri: payload.barri,
                }               
            }
        };
    }
});

localhost:3000/api/v1/poblacios returns the number of women and men from 0 to 95+ years by district, neighbourhood and year, with an id for each row:

[{"id":1,"anny":2015,"districte":1,"barri":"1. el Raval","donesanys0":206,"donesanys1":212,"donesanys2":206,"donesanys3":247....
{"id":2,"anny":2015,"districte":1,"barri":"2. el Barri Gotic","donesanys0":48,"donesanys1":53...
....
{"id":657,"anny":2007,"districte":10,"barri":"73. la Verneda i la Pau","donesanys0":103,"donesanys1":118,"donesanys2":123,"donesanys3":107...

Thanks for your help!




How to upgrade ember.js version

I upgraded ember-cli to version 2.4.3

npm install -g ember-cli

I can see -- ember-cli@2.4.3 , in the listed dependencies, but when I check :

(master *)$ ember -v
version: 2.4.2
node: 5.6.0
os: darwin x64

ember version is still 2.4.2

what's wrong ?




error cannot find module 'balanced-match' in ember

My installed ember cli version 0.2.7, node: 0.12.2,npm: 2.11.0 while start ember server on my application,It shows following error.

Cannot find module 'balanced-match'
Error: Cannot find module 'balanced-match'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)

how to solve this problem?




mercredi 30 mars 2016

Ember-data peekRecord returns null

Ember inspector shows the correct user, but

user: Ember.computed(function(){
    let uid = this.get('user_id'); //the correct ID
    return this.store.peekRecord('user', uid);
}),

Returns null. Might this have something to do with attempting this call outside of the model hook? Really stuck on this!

Thanks so much!




Ember close responsive menu

I am having troubles with closing my responsive menu in Ember. Currently I have a menu icon, if someone presses this, the following action fires:

export default Ember.Controller.extend({
    actions: {
        openMenu() {
            $('#menu').toggle();
        }
    }
});

Which naturally opens my menu. However, when someone presses a link (regardless of where on the page this is) I obviously want the menu to close again. I am finding it difficult how to perform this.

Basically what I want is this:

$('a').click(function() {
    $('#menu').hide();
});

But I simply do not know where to place this code.

I have thought about adding a new helper which mimics the Ember linkTo helper, but I am sure that this would not be the correct solution to the problem. Or is it?

Disclaimer: I am really new to Ember. I use version 2.2 and I do know that they're phasing out controllers, I am working on that too ;).




ember data findRecord returns string

A short question here.

I have the following statement in my route:

user_id: Ember.computed(function(){
    return `${this.get('session.data.authenticated.user_id')}`;
}),

user: Ember.computed(function(){
    let uid = this.get('user_id');
    return this.store.findRecord('user', uid);
}),

But I'm not sure how to work with what it's returning?

<(subclass of Ember.ObjectProxy):ember462>

I ultimately want to use this user object to set up a relation, with this statement:

model(params){
    let user = this.get('user');
    return this.store.createRecord('bizinfo', {'user': user});
},

However when I do, the relation attribute of the record is null.

user: null




Ember data dependent keys undefined

A lot of the other posts on this topic are 2+ years old, so here goes a potentially simple question.

I am using Ember data relationships to have a 'bizinfo' record belong to a 'user' record. Seems simple, but I am having the worst time of it.

In app/models/bizinfo.js I have the line:

'ownedBy': DS.belongsTo('user')

And in my route, where I validate and then save the model, I have the following code:

user_id: Ember.computed(function(){
    return `${this.get('session.data.authenticated.user_id')}`;
  }),

  user: Ember.computed(function(){
    return this.store.findRecord('user', this.get('user_id'));
  }),

  model(params){
    return this.store.createRecord('bizinfo', {'ownedBy': this.get('user')});
  },

at this point if I go into the Ember inspector to look at the 'bizinfo' data object, I see the following under the belongsTo tab:

ownedBy : <(subclass of Ember.ObjectProxy):ember1053>

Here is the code from my submit action:

submit() {
  let model = this.currentModel;
  console.log(model.ownedBy);
  console.log(`what does the model look like?`);
  console.log(model.toJSON());
  model.validate().then(({model, validations}) => {
    if (validations.get('isValid')) {
      this.setProperties({
        showAlert: false,
        isRegistered: true,
        showCode: false
      });
      let success = (response) => {
        console.log(`Server responded with ${response.toJSON()}`);
      };

      let failure = (response) => {
        console.log(`Server responded with ${response}`);
      };
      model.save().then(success, failure);
    } else {
      this.set('showAlert', true);
    }
    this.set('didValidate', true);
  }, (errors) => {
    console.log(`errors from failed validation: ${errors}`);
  });
},

So here is the result of the first console.log statement:

ComputedProperty {isDescriptor: true, _dependentKeys: undefined, _suspended: undefined, _meta: Object, _volatile: false…}

And when I look at the model.toJSON() log, I see

ownedBy: null

Can anyone see what's going wrong here? Is it the create record statement? I have tried a lot of different permutations (such as submitting just the id as the 'user' parameter.




EmberJS: How to make a helper that can return data from a promise

I created a {{findby}} helper that is super useful for picking an item out of an array, but i ran into a problem. The helper does not like to call findBy() on an array which is a promiseArray.

So the helper was modified to do this:

export function findby([array, key, value]) {
  let isPromiseArray = Ember.typeOf(array.then) === 'function';
  if (isPromiseArray) {
    array.then((arr) => {
      return arr.findBy(key, value) || null;
    });
  } else {
    return array.findBy(key, value) || null;
  }
}

export default Ember.Helper.helper(findby);

the idea being of course, if a passed array happens to be a PromiseArray, use a then() before trying to call findBy().

The problem is that I cant seem to return anything in this case.. returning from inside the then() does not seem to actually close out the helper function so the helper returns undefined.

If i try to do:

return array.then((arr) => {
  return arr.findBy(key, value) || null;
});

then just the promise itself gets returned from the helper.

Here is a twiddle of what I have attempted: http://ift.tt/1RLHFhv

THe question seems to be a general one for helpers: Is there a way to return data from a promise/then() function in a helper? I wonder if what i want to do is even possible with a helper?




Ember object attribute is updated but does not get saved to Ember data or model and is absent from payload

displayOrder as object attribute

This is how it looks before the POST request. I am trying to save the displayOrder attribute to the model so that it is included in the payload. But it ends up being null and never receives the data from the attribute object either. Everything else goes into the payload fine.

selectWidget: function(widget) {
  debugger
  var selectedWidget = this.get('selectedWidgets').findProperty('id', widget.id);
  if(selectedWidget){
    this.get('selectedWidgets').removeObject(selectedWidget);
  } else {
    if(this.get('selectedWidgets').length == 0) {
      widget.set('displayOrder', 1);
    } else {
      widget.set('displayOrder', (this.get('selectedWidgets').length + 1));
    }
    widget.set('checked', true);
    this.get('selectedWidgets').addObject(widget);
  }
},

Here I am setting the displayOrder. The set method only adds it as an attribute and not as part of ember _data.

save: function() {
  var self = this;
  debugger
  this.get('rfm_widgets').addObjects(this.get('selectedWidgets'));
  this.set('account_id', this.get('currentUser.account.id'));
  if(this.get('model').validate()) {
    this.get('model')
    .save().then(
      function success(response){
        self.get('selectedWidgets').clear();
        self.get('availableWidgets').forEach(function(widget){
          widget.checked = false;
        });
        self.transitionToRoute('iknow');
        self.get('flash').success(_('<q>%@1<q> profile successfully added'), response.get('name'));
      },
      function error(err){
        Ember.Logger.error('error occured');
      }
    );
  }
},

This is the save method above where I insert the objects into the model. At this point the displayOrder does not go inside.

Profile model:

rfm_widgets: DS.hasMany('rfm_widget', {defaultValue: []}),

Widget model:

name: DS.attr(),
description: DS.attr(),
displayOrder: DS.attr(),
is_active: DS.attr(),
account: DS.belongsTo('account'),
created_by_id: DS.attr(),
created_at: DS.attr(),
updated_by_id: DS.attr(),
updated_at: DS.attr(),

I'm new to Ember and have struggled with this issue for days and have found looked all over the net. Happy to provide more code or description of issue. Many thanks in advance!




Retrieving asset fingerprints in ember-cli addons

When using the ember-cli ember build --environment=production command assets are given fingerprints for cache busting purposes. I was wondering if anyone here knew how to retrieve the fingerprint for a specific file? Would appreciate any suggestions.

The issue this question relates to is here: http://ift.tt/1TiELGt




Ember - how to clean up JSON response

I'm pretty new to EmberJS and unfortunately I have to deal with JSON that doesn't include a root or ids and I can't seem to find any clear way to accomplish what I'm trying to do, which is just to clean up the response.

I assume that I need to be using an ember serializer to do this.

This is what I currently get from my api/locations:

[
  {
    "uri": "/location/1",
    "name": "ATLANTA"
  },
  {
    "uri": "/location/2",
    "name": "NORTH VIRGINIA"
  }
]

I assume that I need it to look like this instead, with a root and id's:

{
   "locations":[
     {
        "id":"1",
        "uri":"/location/1",
        "name":"ATLANTA"
     },
     {
        "id":"2",
        "uri":"/location/2",
        "name":"NORTH VIRGINIA"
     }
    ]
 }

I added a JSONSerializer under app/serializers/location.js

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
    // how can I manufacture an id here, say with index
    // how to I assign it to a root called "locations"
});

Just by including this JSONSerializer I do get a record in the store but it's only one and I assume that's because they don't have ids otherwise both entries would show up.

only one record and no id

I need help and examples of how to begin massaging this data. The examples I have tried didn't do anything.




What is the correct hook for Ember Route to check authorization?

In an Ember.js application, you can use various hooks to check authorization. There are beforeModel, willTransition, redirect hooks on route. also the same events applies on Router.

I'm developing authorization infrastructure for a project. All the route's are written by developers. But an abstract-route (which is extended by all routes) is my code.

  1. If I implement beforeModal or redirect hook in an abstract-route, when a developer writes his own beforeModal methods, my hook will be overwritten.
  2. If I implement willTransition, checking code will be laid on a route that starts transition. From the guide, it seems that willTransition is applicable when leaving the route.
  3. Is it a correct way to handle Router's events?

So what is the correct way to check authorization and abort/prevent transition?




change controller property from another controller

I have an application that has a Navigation bar that I have put in "Application" context. By default, these Navigation bar links will be disabled and will be enabled only on a particular action from template.

The Application controller that contains the disabled status of the link in Nav Bar:-

App.ApplicationController = Ember.Controller.extend({
userName:"TestUser",
firstLinkDisabled:true,
actions:{
    handleToggle:function(){
        console.log("Handling application action with linkstatus="+this.firstLinkDisabled);
        //this.set("firstLinkDisabled",false);
        this.toggleProperty("firstLinkDisabled");
    }
}

})

The Index Controller that will send the action to Application Controller:-

App.IndexController = Ember.Controller.extend({
actions:{
    toggleApplicationButton:function(){
        this.controllerFor("Application").send("handleToggle");
    }
}

})

Application Template:


    <script type="text/x-handlebars">
    
{{#link-to 'first' disabled=firstLinkDisabled}}First link in application{{/link-to}}
<button {{action 'handleToggle'}}>Toggle Application Menu </button> {{outlet}} </script>

Index Template


<script type="text/x-handlebars" id="index">
<button {{action 'toggleApplicationButton'}}>Toggle Application Menu </button>
</script>

When I click on "Toggle Application Menu" button I get the following output in console.

Console Output

But in Ember inspector the property "firstLinkDisabled" doesn't change. Image of Ember Inspector:- Ember Inspector Image

The link remains disabled.

What am I doing wrong here?
Doesn't ember allow to change the property of other controller?
How to make this thing work?




Ember Simple Auth intergration with djoser (django rest framework)

I would like to ask if it's a good practice to use ember simple auth library with djoser. I am using ember for frontend and I would like to use a certain backend made in django. I was wondering if it's better to use ember simple auth library or to try to implement authentication from scratch. I just don't know in what level djoser implements login/logout actions.

Thanks in advance!




mardi 29 mars 2016

preload data after sessionAuthenticated at application route globally

After calling a custom authenticate method at login route, the action sessionAuthenticated is triggered at the application level (ApplicationRouteMixin).

ie:

sessionAuthenticated() {
    this._super(...arguments);

    let _this = this;
    return this_loadUser().catch(function() {
        _this.get('session').invalidate();

    });

}

This works, however, if I want to preload extra data, sessionAuthenticated does not wait until all the promises are resolved. And since the beforeModel and afterModel hooks were already initially at the application route level, the only way this works reliably is when refreshing the page while session is active (logged in).

In short; when at the login route, calling authenticate, after successful authenticate the sessionAuthenticated action is triggered at the application route, but with extra data needed to be preloaded globally, at the application route level. The sessionAuthenticated doesn't see to wait until all promises are resolved.




Ember.js -- how to access data in Ember session from route

Using ember-simple-auth I set up a session and set the currentUser key equal to the user object returned from the server:

setCurrentUser: function () {
    if (this.get('isAuthenticated')) {
        const accountId = this.get('session.content.authenticated.user_id');
        this.get('store').findRecord('user', accountId).then(user => {
            this.set('currentUser', user);
        });
    }
}.observes('isAuthenticated')

Problem is when I am trying to access the 'currentUser' key from a route for a data relation:

user: Ember.computed(function(){
    console.log(this.get('session'));
    //return `${this.get('session.currentUser')}`;
  }),

In the console I see (in addition to a bunch of other stuff):

 currentUser: Class 

but if I try to log 'session.currentUser' I am seeing undefined.

What can I do to access the user ID from this route? Having a lot of trouble with this! Thanks in advance :D




How do I access properties from within an Ember 2 component?

I am having some trouble accessing properties passed to my Ember component, which is as follows:

import Ember from 'ember';

export default Ember.Component.extend({
    isRowEditorActive: function() {
        return this.get('items').length > 0;
    }.property('items'),

    actions: {
        // My actions here
    }
});

The items (list of strings) that I pass in, can be accessed without problems within the template {{line-items-table items=['asd', 'asd']}}

However trying to get them within the component just returns undefined. Any suggestions?




Ember.js -- how to console log a model

Pretty general question here. In my code I am frequently dealing with models:

let model = this.currentModel;

Which seems to be working, but if I

console.log(model);

I see this useless code in the console:

<lc-dash@model:bizinfo::ember904:null>

Does anyone know how to actually log the contents of the model as an object? Also, anywhere I can read about the meaning of this tag?




ember 2 parameters in a action of a select menu

I'm trying to pass more than one argument in an ember action. The problem is that one of the arguments is value='target.value' and apparently Ember doesn't like to add a second one.

How can I pass these two parameters? value='target.value' works if I only need one argument.

I've tried to write it this way but category is undefined.

{{#each selectorsData as |selectorItem|}}
<select onchange={{ action selectorItem.action value='target.value' category='selectorItem.name' }}>

I've tried this way too, but Ember gives me an error

{{#each selectorsData as |selectorItem|}}
   <select onchange={{ action selectorItem.action value='target.value' selectorItem.name }}>

 Error: Parse error on line 4:
 ....value' selectorItem.name }}>




Ember: this.modelFor is not a function (in component)

Question about the Ember method modelFor

My attempts to use this in a component have failed:

//info component

model(params){
return this.store.createRecord('info'); 
},

user: this.modelFor('user'),

this code breaks the entire app with the following error:

ember.debug.js:4875 Uncaught TypeError: this.modelFor is not a function

I find myself often wanting to use methods in components, or wanting to access multiple models in my component logic -- does anyone know a good resource to educate myself on these best practices?

Thanks!




Unable to make custom serializer work even when the "extractArrat" returns data in correct format(ED 1.0.0 beta 17)

I have 2 models which are defined as:

//exercise-concept-zone model
import DS from 'ember-data';

export default DS.Model.extend({
    reportDataId: DS.attr('string'),
    label: DS.attr('string'),
    exerciseZoneCoordinates: DS.hasMany('exercise-zone-coordinate', {async: true})
});


//exercise-zone-coordinate
import DS from 'ember-data';

export default DS.Model.extend({
    x: DS.attr('integer'),
    y: DS.attr('integer'),
    width: DS.attr('integer'),
    height: DS.attr('integer'),
    isHidden: DS.attr('boolean'),
    exerciseConceptId: DS.attr('integer'),
    locale: DS.attr('string'),
    exerciseConceptZone: DS.belongsTo('exercise-concept-zone')
});

The response from the api looks like this:

[{
    "_id": {
        "class": "org.bson.types.ObjectId",
        "date": "2016-03-29T01:54:11Z",
        "inc": 590530557,
        "machine": -33397647,
        "new": false,
        "time": 1459216451000,
        "timeSecond": 1459216451,
        "timestamp": 1459216451
    },
    "reportDataId": "56f6988ffe025821894bd577",
    "label": "A",
    "coordinates": [{
        "isHidden": false,
        "id": "56f9e043fe0264712332c7fe",
        "overlaps": [],
        "height": 90,
        "locale": "en_US",
        "exerciseConceptId": 2,
        "width": 122,
        "y": 11,
        "x": 462
    }, {
        "isHidden": false,
        "id": "56f9e043fe0264712332c7ff",
        "overlaps": [],
        "height": 90,
        "locale": "en_US",
        "exerciseConceptId": 3,
        "width": 122,
        "y": 11,
        "x": 462
    }],
    "id": "56f9e043fe0264712332c7fd"
}, {
    "_id": {
        "class": "org.bson.types.ObjectId",
        "date": "2016-03-29T02:03:21Z",
        "inc": -1254788286,
        "machine": -33422994,
        "new": false,
        "time": 1459217001000,
        "timeSecond": 1459217001,
        "timestamp": 1459217001
    },
    "reportDataId": "56f6988ffe025821894bd577",
    "label": "B",
    "coordinates": [{
        "id": "56f9e269fe02016eb5357343",
        "isHidden": false,
        "overlaps": [],
        "height": 94,
        "width": 148,
        "exerciseConceptId": 2,
        "locale": "en_US",
        "y": 186,
        "isInvalid": false,
        "x": 279
    }, {
        "id": "56f9e269fe02016eb5357344",
        "isHidden": false,
        "overlaps": [],
        "height": 94,
        "width": 148,
        "exerciseConceptId": 3,
        "locale": "en_US",
        "y": 186,
        "isInvalid": false,
        "x": 279
    }],
    "id": "56f9e269fe02016eb5357342"
}]

And finally my exercise-concept-zone serializer looks like this:

//serializers/exercise-concept-zone
import DS from 'ember-data';

export default DS.JSONSerializer.extend({

    extractArray: function(store, typeClass, arrayPayload, id, requestType) {
        let normalizedPayload = this.normalizePayload(arrayPayload);
        let returnPayload = {exerciseConceptZones: [], exerciseZoneCoordinates: []};

        normalizedPayload.forEach((singlePayload)=> {
            let normalizedSinglePayload = this.normalize(typeClass, singlePayload);
            (returnPayload.exerciseConceptZones).pushObject(normalizedSinglePayload.exerciseConceptZone);
            (returnPayload.exerciseZoneCoordinates).pushObjects(normalizedSinglePayload.exerciseZoneCoordinates);
        });
        return returnPayload;
    },


    normalize: function(typeClass, hash) {

        let zoneCoordinates = [];

        zoneCoordinates.pushObjects((hash.coordinates).map((coordinate)=> {
            delete coordinate._id;
            delete coordinate.overlaps;
            coordinate.exerciseConceptZone = hash.id;
            return coordinate;
        }));
        hash['exerciseZoneCoordinates'] = (hash.coordinates).map((zoneCoordinate)=> {
            return zoneCoordinate.id;
        });

        delete hash.coordinates;
        delete hash._id;

        let returnPayload = {exerciseConceptZone: hash, exerciseZoneCoordinates: zoneCoordinates};

        return this._super.apply(this, [typeClass, returnPayload]);
    }    

});

And then my response serializers' extractArray is properly formatted to return final payload like this:

{
    "exerciseConceptZones": [{
        "reportDataId": "56f6988ffe025821894bd577",
        "label": "A",
        "id": "56f9e043fe0264712332c7fd",
        "exerciseZoneCoordinates": ["56f9e043fe0264712332c7fe", "56f9e043fe0264712332c7ff"]
    }, {
        "reportDataId": "56f6988ffe025821894bd577",
        "label": "B",
        "id": "56f9e269fe02016eb5357342",
        "exerciseZoneCoordinates": ["56f9e269fe02016eb5357343", "56f9e269fe02016eb5357344"]
    }],
    "exerciseZoneCoordinates": [{
        "isHidden": false,
        "id": "56f9e043fe0264712332c7fe",
        "height": 90,
        "locale": "en_US",
        "exerciseConceptId": 2,
        "width": 122,
        "y": 11,
        "x": 462,
        "exerciseConceptZone": "56f9e043fe0264712332c7fd"
    }, {
        "isHidden": false,
        "id": "56f9e043fe0264712332c7ff",
        "height": 90,
        "locale": "en_US",
        "exerciseConceptId": 3,
        "width": 122,
        "y": 11,
        "x": 462,
        "exerciseConceptZone": "56f9e043fe0264712332c7fd"
    }, {
        "id": "56f9e269fe02016eb5357343",
        "isHidden": false,
        "height": 94,
        "width": 148,
        "exerciseConceptId": 2,
        "locale": "en_US",
        "y": 186,
        "isInvalid": false,
        "x": 279,
        "exerciseConceptZone": "56f9e269fe02016eb5357342"
    }, {
        "id": "56f9e269fe02016eb5357344",
        "isHidden": false,
        "height": 94,
        "width": 148,
        "exerciseConceptId": 3,
        "locale": "en_US",
        "y": 186,
        "isInvalid": false,
        "x": 279,
        "exerciseConceptZone": "56f9e269fe02016eb5357342"
    }]
}

My serializers' response does match the json payload format, but still my exercise- zone-model fails to resolve.




How to bubble up error from Ajax call in controller to application-error route

I was wondering how we can bubble up the error we get from ajax call failure to application-error route. I noticed the error structure i get is quite different than what we have passed as one of the parameters to 'error' action in application route. does anyone know how this can be done i'm new with Ember

 error: function(error, transition) {
      return true;
    }




How to set URI correctly in a cordova project?

I use cordova-cli to build an android app. The app can not access resource correctly. The error is

Failed to load resource: net::ERR_FILE_NOT_FOUND

And I found the URI is

file:///assets/media/images/stop-sm.png

I think it should be

file:///android_asset/www/assets/media/images/stop-sm.png

but I don't know where and how to set the URI correctly. Any advices or hints are appreciated. Thanks in advance.

[www]
  [assets]
    [media]
      [images]
         stop-sm.png
   xxx.js
   xxx.css
 index.html




Determine whether scroll to bottom in div

I have ember app.In which I have icon in navbar which when clicked show a dropdown with notification.I have set the max-height of dropdown as 390px.Now I want to determine when the user has reached the bottom to the dropdown so that I can make an ajax call to the server for more data.

html

<div class="ps-content">
.....notification content.....
</div>

css

.ps-container{
  max-height: 390px;
  position: relative;
}

js

didInsertElement: function(){
    $('.ps-content').on('scroll', $.proxy(this.didScroll, this));
  },
  willDestroyElement: function(){
    $('.ps-content').off('scroll', $.proxy(this.didScroll, this));
  },

  didScroll: function(){
    if (this.isScrolledToBottom()) {
      this.sendAction('loadMore');
    }
  },

  // we check if we are at the bottom of the page
  isScrolledToBottom: function(){
      var distanceToViewportTop = WHAT SHOULD I AM DO HERE ?
      var viewPortTop = $('.ps-content').scrollTop();
      if (viewPortTop === 0) {
        return false;
      }   
      return (viewPortTop - distanceToViewportTop === 0);
  },

when I do $('.ps-content').height it is giving 390px.How to get the whole content height render into the dropdown ?

In the "viewPortTop" I am getting how much user has scrolled.But I am not able to figure out what should I do "distanceToViewportTop" So that When user reaches at bottom there difference is zero.I can't use documnet height and window height as it takes the whole page height.For Whole page it is documnet - window height to get the bottom page.What should I do for div ?




How can I update component value in controller or route with ember?

My click-editable component like:

Template:

{{#if isEdit}}
  <div class="input-group">
    {{input type="text" value=editValue class="form-control"}}
    <div class="input-group-btn">
      <button type="button" class="btn no-margin-btn btn-info" {{action "updateValue"}}>{{fa-icon 'check'}}</button>
    </div>
  </div>
{{else}}
  ....
{{/if}}

And:

export default Ember.Component.extend({
  tagName: "",
  isEdit: false,
  canEdit: true,
  category: 'input',
  editValue: Ember.computed.oneWay('value'),

  actions:{
    updateValue() {
      this.sendAction('onUpdate', this.get('valueModel'), this.get('valueColumn'), this.get('editValue'), this.get('isEdit'));
    }
  }
});

Use in my template:

{{click-editable valueModel=quotationWorkItem valueColumn='name' value=quotationWorkItem.name onUpdate=(action "updateInput")}}

In the controller:

import Ember from 'ember';

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

  actions: {
    updateInput(updateModel, updateColumn, value, isEdit) {
      updateModel.set(updateColumn, value);
      updateModel.save().then(()=> {
        this.get('model').reload();
        this.set('isEdit', false);
      }, ()=> {
        alert('wrong');
      });
    }
  }
})

This code can update model value, but problem isEdit is the component value. When isEdit send to controller and set another value, it can not work. So I think can not change component value in ember controller?

this.set('isEdit', false);

The code can not work in controller. I'm using Ember 2.4.0.




Duplicate records showing up in template

I have a survey app built with Ember JS and a Firebase backend with Emberfire adapter.

Here are the relevant portions of my user model:

//app/models/user.js
export default DS.Model.extend({
  name: DS.attr(),
  sessionuid: DS.attr(),
  surveysToTake: DS.hasMany('survey', { async: true, inverse: 'respondents' }),
  surveysCreated: DS.hasMany('survey', { async: true, inverse: 'creator' }), 
  responseSetsSubmitted: DS.hasMany('response-set', {async: true, inverse: 'respondentid'}),
  respSetSurveyLookup: DS.attr({defaultValue: function() { return []; }}) 
});

And my responseSet (which is a collection of responses from a user)

//app/models/response-set.js
export default DS.Model.extend({
  responses: DS.hasMany('response', { async: true, inverse: 'responseSet' }),
  survey: DS.belongsTo('survey', { async: true, inverse: 'responseSets' }),
  respondentid: DS.belongsTo('user', {async: true, inverse: 'responseSetsSubmitted'}),
});

And the survey model looks like this:

//app/models/survey.js
export default DS.Model.extend({
  title: DS.attr(),
  questions: DS.hasMany('question', { async: true, inverse: 'survey' }),
  respondents: DS.hasMany('user', { async: true, inverse: 'surveysToTake'}),
  responseSets: DS.hasMany('response-set', { async: true, inverse: 'survey' })
});

Now, when creating a user we do something like this ...

//routes/addusers.js (in the actions hook after getting properties from the controller)

var user = store.createRecord('user', {
            id: userData.uid,
            name: name   
          });
var responseSet = store.createRecord('response-set', {
            survey: survey,
            respondentid: user
          });

Ember.set(user, 'respSetSurveyLookup', [{'surveyId': _this.currentModel.get('id'),
                                         'respSetId': responseSet.get('id')}]);
Ember.set(user, 'surveysToTake' ,[_this.currentModel]);
_this.currentModel.get('respondents').pushObject(user);
Ember.RSVP.all([user.save(), _this.currentModel.save(), responseSet.save()])
   .then(function(){
      controller.setProperties({ multipleUsers: '', showAddUsers: false});
});

The user gets added as expected. However, in my template (which shows up on the same route as the 'add users' section, the same record shows up multiple times.

Additional info:

  • I'm using Ember 1.13.11 with Ember Data 1.13.11 and EmberFire 1.6.3
  • Refreshing the page or reloading (with a 'location.reload()' ) causes the user records to show up as expected.

This is possibly related to an Ember data issue which appears to be now closed and an upgrade of Ember data may resolve this in the future. However, is there anything I can do in the meantime to handle this issue ?




Ember - Customize adapter not to use model name

I would like to ask a question about ember model and adapter. I have a model named account, used user creation. I would like not to use the model name in the url but when I try to create a user and communicate with the backend (http://ift.tt/1RMM3mT), ember keeps trying to connect to http://ift.tt/22WVRfC.

In the application RESTAdapter:

I have declare:

and my buildURL is shown below:

buildURL: function(modelName, id, snapshot, requestType, query) {

    var url = this._super(modelName, id, snapshot, requestType, query);

    if (requestType == "createRecord" && modelName == "account")  {
        url = url + "register/"
    }

    return url;
}




lundi 28 mars 2016

Ember.js What should be made a Component?

Basically, if you were given a design of a web page with all kinds of UI patterns/elements, some with interaction and some just static, how would you decide what should be made into a component and what can just stay as html?

This is more of a philosophical question and goes beyond Ember.js; I included it because thats what I'm learning/using right now.

There are some patterns which should obviously be implemented as components, such as tab switchers or filters and my naive reasoning is that they have interaction and are used multiple times on the page. But how far do I go with that? Are each of these reasons sufficient to justify a component or are they only necessary or are they neither? Should a make a button component just because there are many buttons on the page? Should I make a slider component even if I know there will only ever be one slider on the page?

What are good rules of thumb to decide whether to implement something as a component? I could envision creating components for every single thing so that the entire page is just components within components. Surely that is too far? Especially given that Ember's components each have an instantiation cost and lifecycle, theres also a performance aspect to consider when deciding what should be a component right?

I'm interested to hear everybody's viewpoints. Thanks.




Observing changes to an embedded record of an ember-data model

I have an Ember component that is passed a model:

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

source has many nested embedded records. models/source.js is defined as:

export default Model.extend({
  displayName: attr('string'),
  azureStorageName: attr('string'),
  sourceInstances: DS.hasMany('source-instance')
});

models/source-instance.js:

export default Model.extend({
  status: attr('number'),
  creatorId: attr('number'),
  blobName: attr('string'),
  created: attr('date'),
  conversionLogs: DS.hasMany('conversion-log')
});

and so on...

My controller periodically polls the backend for source data, and I can see this reflected in Ember Observer, with the embedded documents being updated successfully. From the component, I would like to react to changes to the embedded records of the source records. I have looked at the following QAs and some others and still cannot figure out a way:

Observe Ember Data store changes in component

How to observe for changes in the Ember data store?

What is the simplest way to be able to observe changes to embedded records of an ember-data model? Note that these embedded records do not have endpoints on the backend.

I am using Ember 2.4.3.




Ember.js 2 How to filter an existing model?

I'm currently learning Ember 2, and I'm trying to figure out the best approach to stacking model filters in Ember.js (2.4.2 with CLI workflow) and Ember Data.

Specifically, I am wondering if there is a good way to apply filters to an existing route's filtered model, without overriding any filtering that the route (or other component) itself may be doing.

My problem is this:

I have log entries (model "entry") which are sorted by date and associated with a user by user ID (model "user").

Model as defined in /app/routes/index.js:

export default Ember.Route.extend({
  // ...

  model: function() {
    return Ember.RSVP.hash({
      users: this.store.findAll("user")
      entries: this.store.findAll("entry")
    });
  },

  // ...
});

Model is overwritten in /app/routes/user.js:

export default Ember.Route.extend({
  // ...

  model: function() {
    return Ember.RSVP.hash({
      users: this.store.findAll("user")
      entries: this.store.filter("entry", function(entry) {
        // ...
        return entry.get("userId") === userId;
      })
    });
  },

  // ...
});

When viewed, localhost:4200/ lists all entries, and localhost:4200/user/alice lists all entries owned by the user named "alice". Likewise, localhost:4200/user/bob lists all entries by user "bob".

I also have a filtering component that allows entries to be filtered by date.

Specifically, entries on or after a "from" date, and/or entries on or before a "to" date. These date filters need to be able to applied to both the index and user routes.

The problem comes in with the user route. I can do the following in /app/components/log-filter.js to filter by date (assume this.entries is the "entry" model passed as a template attribute from the current route):

// ...

var filtered = this.entries.store.filter("entry", function(entry) {
  var logDate = entry.get("logDate");
  return logDate >= filterDateFrom && logDate <= filterDateTo;
});

this.set("entries", filtered);

This code properly filters by "date from" and "date to", but it overrides the user name filtering when run in the user route.

The quick and dirty route would be to replicate the user name filtering in the date filter callback, but this is not DRY and it will quickly become unwieldy as more routes are added (category, location, etc.), since date filters need to be universal.

My question

  1. Is there any way to filter against an existing model, rather than always starting with the global *.store.filter("modelName", callback) collection?
  2. Is this even a good approach or is there a better, more "Ember" way of handling multiple arbitrary filters?

Any help at all is appreciated.




jquery: unexpected token C using ember

Here's my error:

SyntaxError: Unexpected token C
    at Object.parse (native)
    at jQuery.parseJSON (http://localhost:4200/assets/vendor.js:8219:14)
    at ajaxConvert (http://localhost:4200/assets/vendor.js:8501:19)
    at done (http://localhost:4200/assets/vendor.js:8962:15)
    at XMLHttpRequest.<anonymous> (http://localhost:4200/assets/vendor.js:9378:9)

I'm not sure where to go from here. I'm able to pull data from my backend json api with no problems, but when I try to save data, I just get that jquery error. I'm using the following call:

addObject(newObject) {
  newObject.save().then(() => this.transitionTo('page.index'));
}

I've read the jquery error has to do with the fact that it's trying to parse a json object into json, but since this is being done by ember, I'm not sure if I'm missing a step somewhere.

If anyone has any ideas of the right direction to look, I'd appreciate it.




Pass variable from initializer to handlebars .hbs (Discourse Plugin, maybe Ember in general)

In a .hbs file I am creating a navigation menu with various items. One of the items will only display if a user is a pro (boolean).

var pro is a variable set in my initializer and I need to pass it my .hbs file for the purposes of a conditionally showing one of the menu items.

In Ember, how is this accomplished?




How to glue together Jersey Jax-RS with Ember's DS.RESTADAPTER?

Being quite new to Ember framework I ran into a problem on how to adapt the Jersey/Grizzly REST API for Ember frontend. Ember documentation assumes JSON API follows the standard. It suggests to write REST adapter but even it this case of writing custom adapter it seems to apply strict rules: The JSON payload should be an object that contains the record inside a root property.

My application is almost identical to Official Java 8 Tutorial):

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Collection;

@Path("/items")
public class ItemsRest {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Collection<Item> findItems() {
        return new ItemsService().getItems();
    }
}

ItemsService uses com.fasterxml.jackson.databind public class ObjectMapper. Jersey uses Jackson to handle the JSON conversion automatically but the resulted JSON cannot be parsed by Ember.

The response it prints out is in this format:

[{"id":1, "name":"examle", "otherProperties":"value"}, {...etc...}]

I need to create REST API on backend and provide some Javascript framework to handle it with no troubles.

What is the smartest and most straightforward approach? How to write Ember's DS.RESTADAPTER so it would be able to handle my data? Should I modify backend with something like this library jsonapi-converter?

Should I ditch Ember in favor of AngularJS or other frameworks that is less strict in terms of json api format/structure?

PS. Ember v2.4.0




How to catch the changed Object in ember.js observer

How to get the changed Object in ember observer? My code.




How to get to error route from locally handling ajax calls

I have an ajax util which is responsible for sending POST and GET request and on the success i always do some calculation and on error i want to be routed to application error route. Here is my code in my controller. I dont fully understand how routing to application error route works.

var error = function (xhr, status, error) {          
               // what to be done here to go to error route 
            };
 var success = function (response) {
                          //my calculation code
                        };

self.ajaxUtil.send(url, 'GET', success, error, JSON.stringify(payload), 'json', 'application/json', true, ajaxHeaderInfo,self.get('store'));




Ember-Simple-Auth encoding request header application/x-www-form-urlencoded, Rails server expects application/json

We are building a WebApp for a school project using an Ember 2.2.3 frontend with Rails 4.2.5 and Postgres 5.7 on the back. We have ran into a problem authenticating and cannot find a relevant solution. We believe ember should be encoding our email and password into JSON for authentication, and Rails is expecting a JSON object for validate and return a token. But what is actually happening is that Ember is sending a application/x-www-form-urlencoded version of the email and password, so Rails will throw a 415 Unsupported Media Type Error. We followed this tutorial for authentication:

http://ift.tt/1iWJyyD

Is there a way in Ember to change this encoding to application/json? or could we change Rails to accept application/x-www-form-urlencoded?

Here is our current authentication request header:

POST /users/sign_in HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 63
Accept: application/json, text/javascript
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8




Test route inside Ember application

We've created a custom Ember compiler, which allows to introduce user roles inside the Ember application.

This method makes sure that a custom app.js is generated, containing only the routes/controllers that the user has access to, based on it's user role.

Is there a method available to test if a specific Ember route (by name) is available, so I can hide/show specific menu items?

We are currently using Ember v2.0.2.




Can I build a link-to using the current route name?

I have foo, bar then foo.baz, bar.baz. Can I call {{link-to}} in such a way that it refers to the current route instead of having to use the fully qualified name in each case?




embed {{link-to}} inside html tag

How to embed link-to inside html button tag ?

This is what i have tried -

<button {{link-to "posts.show" post}}> Show </button>

Getting Uncought Error: There is no route named

embercli@model:post::ember506:6




Ember, component to redirect

in my ember app I have an activities route, with corresponding route, controller and a few components, the template contains:

{{carousel-activities activities=model}}

the carousel-activities contains:

{{#each activities as |activity|}}
    <li>{{carousel-block activity=activity}}</li>
  {{/each}}

the carousel-block contains some HBS to show the content of each activity:

<div class="carousel-block">
  {{#link-to 'activity' activity class="small"}}
    <div class="full-width-image">
      <img src="{{activity.image}}" class="img img-responsive full-width" alt="{{activity.title}}">
    </div>
    <div class="text-center">
      <h1>{{activity.title}}</h1>
    </div>
  {{/link-to}}
</div>

The block component uses ember-gestures to monitor the panDown, when the event happens the block will redirect the browser to the activity details page.

#app/controllers/activities.js
import Ember from 'ember';

export default Ember.Controller.extend({

});


#app/components/carousel-activities.js
import RecognizerMixin from 'ember-gestures/mixins/recognizers';
import Ember from 'ember';

const {
  Component
} = Ember;

export default Component.extend(RecognizerMixin, {
  recognizers: 'pan',
  panDown() {
    console.log("panDown");
    this.transitionTo('activity', this.get('activity'));
  }
});


#app/components/carousel-block.js
import Ember from 'ember';

export default Ember.Component.extend({
});

If I load the activities route, and swipe down on it (raise the panDown event) I get this error in the console:

panDown
ember.debug.js:6208 DEPRECATION: Ember.View#transitionTo has been deprecated, it is for internal use only [deprecation id: ember-views.view-transition-to]
        at HANDLERS.(anonymous function) (http://localhost:4200/assets/vendor.js:16380:7)
        at raiseOnDeprecation (http://localhost:4200/assets/vendor.js:16290:12)
        at HANDLERS.(anonymous function) (http://localhost:4200/assets/vendor.js:16380:7)
        at invoke (http://localhost:4200/assets/vendor.js:16396:7)
        at deprecate (http://localhost:4200/assets/vendor.js:16349:32)
        at Object.deprecate (http://localhost:4200/assets/vendor.js:26468:37)
        at _emberMetalMixin.Mixin.create.transitionTo (http://localhost:4200/assets/vendor.js:52805:24)
        at panDown (http://localhost:4200/assets/myproject.js:261:12)
        at _emberRuntimeSystemObject.default.extend.trigger (http://localhost:4200/assets/vendor.js:55654:23)
ember.debug.js:42747 Uncaught TypeError: Cannot read property 'enter' of undefined_emberMetalMixin.Mixin.create._transitionTo @ ember.debug.js:42747_emberMetalMixin.Mixin.create.transitionTo @ ember.debug.js:42736panDown @ carousel-activities.js:24_emberRuntimeSystemObject.default.extend.trigger @ ember.debug.js:45584superWrapper @ ember.debug.js:23209Backburner.run @ ember.debug.js:678Backburner.join @ ember.debug.js:702run.join @ ember.debug.js:21280_emberMetalAssign.default.handleEvent @ ember.debug.js:46458exports.default._emberMetalMixin.Mixin.create._Mixin$create.handleEvent @ ember.debug.js:43395exports.default._emberRuntimeSystemObject.default.extend._bubbleEvent @ ember.debug.js:44482(anonymous function) @ ember.debug.js:44424jQuery.event.dispatch @ jquery.js:4737elemData.handle @ jquery.js:4549triggerDomEvent @ hammer.js:2497Manager.emit @ hammer.js:2438emit @ hammer.js:1474Recognizer.emit @ hammer.js:1485inherit.emit @ hammer.js:1764Recognizer.tryEmit @ hammer.js:1502Recognizer.recognize @ hammer.js:1549Manager.recognize @ hammer.js:2314inputHandler @ hammer.js:517MEhandler @ hammer.js:826Input.domHandler @ hammer.js:430




How to binding an external host for ruby on rails?

I deployed my ruby on rails project on a different virtual instance, and I changed the binding IP to an external floating IP by append this code to /config/boot.rb:

require 'rails/commands/server'
module Rails
  class Server
    def default_options
      super.merge(Host:  '199.116.235.154', Port: 3000)
    end
  end
end

and it can also be find in this answer. However, when I start the server by: rails s, I got this error:

> /home/ubuntu/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/puma/binder.rb:240:in
> `initialize': Cannot assign requested address - bind(2) for
> "199.116.235.154" port 3000

I know it is because 199.116.235.154 was an external host, so puma won't grant the access for me. And when I change it to internal IP: 10.2.3.52, it runs, but I can't target 10.2.3.52 from my phone browser or other computer. So, is there any way for me to make the public 199.116.235.154 IP work for me?

Also, my frontend was built in a different directory by ember. They communicate with each end through jsonAPI, and currently I'm using localhost for debugging purpose:

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
  // Connect to Rails server
  host: 'http://localhost:3000',
});

If I can make 199.116.235.154 host for my ruby on rails backend, will it also work for my ember frontend by changing localhost to 199.115.235.154?




dimanche 27 mars 2016

How to design API so it would fit REST conventions and Ember.js way?

Would be a good practice to merge all properties of Item:

{id: 1, priceId:1, property1:0} with its corresponding Price {id:1,seasonalPrice:123,regularPrice:120} into:

{id:1,property1:0, price:{seasonalPrice:123,regularPrice:120}}.

Ember most likely can handle linking and combining(merging) two jsons that arrive as two promises from backend REST API into one model. What is the best approach?




How to get property from component when testing?

How can I check component's property value when component doesn't have template? In application the component is extended and template is provided that way.

//my-component.js
export default Ember.Component.extend({
    foo: 'bar'
});

//my-component-test.hbs
integration: true;
test('it renders', function(assert) {
  this.set('foo2', 'foo2');
  this.render(hbs`{{my-component foo=foo2}}`);
  assert.equal(/* ??? */, 'foo2');
});

I am not able to use this.render(hbs'{{#my-component foo=foo2}}{{foo}}{{/my-component}}'); because foo is not yielded. Accessing component directly is not possible either.




samedi 26 mars 2016

A sample for ember.js SPA webapp connect WSO2 API manager rest api and WSO2 Identity Server for sso

A sample project for ember.js SPA webapp connect WSO2 API manager rest api and WSO2 Identity Server for sso.




Ember app not reading API, using hapijs I believe my API is fine just an ember issue

so I started building an app that uses ember and hapi to learn both.

I have pasted the snippets below but I also have both the server and ember app available in a repo here, http://ift.tt/1MsNQLv if you are interested in viewing what I have there.

I have my hapi server showing the below from my sql server

{"data":[{"id":1,"first_name":"Joe","middle_initial":null,"last_name":"Smith","title":null,"phone_number":"(555) 111-2222","email":"jsmith@test.net","street_address":"123 Some Street","city":"Salt Lake City","state":"Utah","zip_code":"84111","created_at":1456988902625,"updated_at":1456988902625},{"id":2,"first_name":"John","middle_initial":null,"last_name":"Jones","title":null,"phone_number":"(555) 222-3333","email":"jjones@test.net","street_address":"1432 Another Street","city":"Montgomery","state":"Alabama","zip_code":"99291","created_at":1456988902625,"updated_at":1456988902625},{"id":3,"first_name":"Joe","middle_initial":null,"last_name":"Smith","title":null,"phone_number":"(555) 111-2222","email":"jsmith@test.net","street_address":"123 Some Street","city":"Salt Lake City","state":"Utah","zip_code":"84111","created_at":1457588539468,"updated_at":1457588539468},{"id":4,"first_name":"John","middle_initial":null,"last_name":"Jones","title":null,"phone_number":"(555) 222-3333","email":"jjones@test.net","street_address":"1432 Another Street","city":"Montgomery","state":"Alabama","zip_code":"99291","created_at":1457588539468,"updated_at":1457588539468}]}

at

http://localhost:3000/api/contacts

my ember app has these files below containing,

adapters/application.js,

  1 import DS from 'ember-data';
  3 export default DS.JSONAPIAdapter.extend({
  4   namespace: 'api',        
  5   host: 'http://localhost:3000'
  6 });

models/contact.js,

  1 import DS from 'ember-data';

  3 export default DS.Model.extend({
  5   firstName: DS.attr('string'),
  6   lastName: DS.attr('string'),
  7   middleInitial: DS.attr('string'),
  8   title: DS.attr('string'),
  9   phoneNumber: DS.attr('string'), 
  10   email: DS.attr('string'),
  11   streetAddress: DS.attr('string'),
  12   city: DS.attr('string'),
  13   state: DS.attr('string'),
  14   zipCode: DS.attr('string'),
  15   createdAt: DS.attr('date'),
  16   updatedAt: DS.attr('date')  
  17 });

routes/contacts.js

  1 import Ember from 'ember'; 
  2                            
  3 export default Ember.Route.extend({
  4     model: function(){     
  5         return this.store.findAll('contact');
  6     }                      
  7 });

I also set this up under serializers/application.js but dont think its necessary since I dont need to normalize anything

  1 import DS from 'ember-data';
  2 
  3 export default DS.JSONAPISerializer.extend({
  4   primaryKey: 'id',
  5   serializeId: function(id) {
  6     return id.toString();
  7   }
  8 });

templates/contacts.hbs

  1 <ul>  
  2   {{#each contact in model}}
  3       <li>{{#link-to 'contact' contact}}{{contact.firstName}}{{/link-to}}</li>
  4   {{/each}}
  5 </ul>  
  6 
  7 {{outlet}}

All Im expecting is the contacts route to just show the list currently from the api, I am not done with this yet and have been stuck here for some time.

the console errors I get are,

ember.debug.js:28590 Error while processing route: contacts.index Assertion Failed: You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from (unknown mixin) Error: Assertion Failed: You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from (unknown mixin)

and

Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using contacts-app@serializer:application:)




Arbitrary query params on Ember.js

In Ember.js, query-params can be used with link-to to generate links that include a query string. For instance:

<p>{{link-to "Search" 'search' (query-params q='london')}}</p>

What is not immediately apparent is how to pass arbitrary parameters to query-params. This is: passing an object whose key/values will make the query string. For example the following (which throws an error):

// At the component
myParams: {
  q: 'london',
},

{{!-- At the template --}}
<p>{{link-to "Search" 'search' (query-params myParams)}}</p>

<!-- The end result -->
<p><a href="/search?q=london">Search</a></p>

Looking at Ember's source code, I can see how this can be done. I can put together an object that looks like those returned by query-params. True enough, the following object will be interpreted by link-to the way I want:

// At the component
myParams: {
  isQueryParams: true,
  values: {
    q: 'london',
  },
},

{{!-- At the template --}}
<p>{{link-to "Search" 'search' myParams}}</p>

However, that looks like an internal, private interface to me. So my question is: is there an approved way to do this? (And what is it?)




How to access a routes model in Ember 2

I am having some trouble accessing my route's model inside my template. My model is created successfully as part of an action defined in my home controller:

actions: {
    createProject: function () {
        var project = this.store.createRecord('project', {
            name: 'Sample name'
        });
        var self = this;
        var promise = project.save();

        promise.then(function (response) {
            self.transitionToRoute('estimate', project);
        });
        promise.catch(function (errors) {
            console.log(errors);
        });
    }
}

The model's uuid is correctly serialized into the URL, with the URL inside my router.js being as follows:

  this.route('estimate');
  this.route('estimate', { path: '/estimate/:project_id' });

My estimate controller also correctly specifies the project dependency:

import Ember from 'ember';

export default Ember.Controller.extend({
    needs: ['project']
});

...and I define the model inside my routes/estimate.js as follows:

import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    // model: function(params) {
    //     return this.store.find('project', params.project_id);
    // },
    model(params) {
        return this.store.findRecord('project', params.project_id);
    }
});

Logging the output of this.store.findRecord('project', params.project_id) I get:

Class {__ember1458995391969: null, __ember_meta__: Meta}
__ember1458995391969
...

However when I try to access the project model inside my estimate handlebars template (using {{model.project.name}}), I get nothing (no errors, no output).

Anybody have any thoughts on this?




Ember.js - How to handle error with DS.store.findRecord() method

I am using following simple code to retrieve user from server.

var someUser = this.store.findRecord('user', 0);

I am using this for retrieving the user. if user is not found on 0 id,

server returns 404. and error as per json api.

but how do i know about error on client side about it ?




No data displayed in Financial table using addepar

I installed ember2.4.2 and installed ember-table using ember install http://ift.tt/1RrDbgL Simple table and editable table worked after i copied all relevant files (I copied all relevant files for these two table eg and i worked properly) But when i did the same for Financial table Sometimes console error Uncaught TypeError: _ember.default.Handlebars.makeBoundHelper is not a function at fa-icon.js:92 Comes and nothing is displayed. Otherwise

the table outline comes but not data in on all RHS <span class="ember-table-content"> <!----> </span> and all LHS <div id="ember629" style="width:400px;" class="ember-view ember-table-cell ember-table-table-tree-cell text-align-left"><!----></div> But no data. also get

Can you please let me know what is the issue.




vendredi 25 mars 2016

Ember.Test - using the module in integration tests for components

I'm trying to import Ember.Test into an integration test that I have for a component in order to use the test helpers that are bundled with the module.

Is there an easy way to do that without initializing an application?




Where should ember-cli-rails compile the app in production?

During asset:precompile ember-cli-rails will build the ember app into tmp/ember-cli/apps/<appname>. This places the app in <appname>-<hash>.js in the compiled app assets (that is in tmp/ember-cli/<appname>/assets/<appname>-<hash>.js). include_ember_script_tags <:appname> will ask for the correct assets/<appname>-<hash>.js but this will not be served by a productions server configured to let assets be served by Apache/Nginx.

Shouldn't the ember-cli-rails compile the app into public/assets in production mode, so they are visible to Apache/Nginx?

Or should I set rails to serve the app from where ember-cli-rails place it:

config.serve_static_assets = true
config.assets.paths << Rails.root.join('tmp', 'ember-cli', 'apps', '<appname>', 'assets')




Create custom filters on filter initialization in Kendo grid

i want to create a custom filter as shown in the screenshot, once the user click on the filter (on filter initialization ), i want to add a list of unique values (returned as an ajax response) to the default filter and users will be able to select multi items. I was wondering how it can be done.enter image description here




textPath not in the right place when using Ember

I build a small, example Ember application that relates to an issue I am having. In it, I have an SVG drawing with a path and a textPath element on it. Unfortunately, the textPath does not show up, it has 0 height and width in the browser, and is in the wrong position.

Here is an ember-twiddle illustrating the bug. There should be text "Hello World" following the arc. In Chrome 48 this worked fine, but in Chrome 49, it does not. It also does not work in the latest version of Firefox.

Is this a bug with Ember or the browsers? Is there a way to work around this bug?

I filed an issue with Ember, though haven't gotten any response. It is strange that it worked in Chrome 48, but now in 49 it does not. The twiddle doesn't work in Safari for me, but my other testing shows that it works fine in Safari. IE11 also appears to be fine.




Ember.js Render Only Once

So I have an Ember application that is very "stupid". It has a bunch of components for displaying various formats of data (tree, table, list, etc). It has 1 route, which is a complete wildcard. When you go to a url, Ember requests the same url resource from the server. If the resource is of type "table", it renders the "table" component and display the data. It does the same for any other type.

This works great. But the user needs a navigation bar. So Ember requests a list of all "pages" from the server and creates a navigation bar. The problem is, it rerenders the navigation bar every time you change pages.

How can I make the nav component request the data and load and then not be rerendered? The "Help" button on the navbar is displayed if the page has a help file otherwise it is not displayed. So the navbar is not exactly the same on every page. I can remove the help button from the navbar if it is easier. Thanks.

Route JS:

import Ember from 'ember';
import util from '../utils/utilities';

export default Ember.Route.extend({
  model() {
    var path = this.get('router.url');
    path = path.replace(/^\/|\/$/g, '');
    if (path === '') {
      path = 'Home';
    }

    var model = {
      navigation: null,
      page: null,
      api: path.replace(/\//g,"_")
    };

    util.httpGet('pages').then(function(navigation) {
      util.getPaths(path).map(function(path) {
        return util.setActive(navigation, path);
      });
      Ember.set(model, 'navigation', navigation);
    });

    util.httpGet('pages/' + model.api).then(
      function(page) {
        if (page.location[0] === 'special') {
          page.location = [];
        }
        Ember.set(model, 'page', page);
      },
      function(error) {
        var page = {
          title: error.status + ' Error',
          type: 'text-viewer',
          text: error.statusText
        };
        Ember.set(model, 'page', page);
      });

    return model;
  }
});

Route HBS:

{{navbar-component
  model=model
}}

<div class="page">
  <div class="pageHeader">
    {{#if model.page.location}}
      <ol class="breadcrumb">
        {{#each model.page.location as |item|}}
          <li>{{item}}</li>
        {{/each}}
        <h2 style="margin: 5px 0;">{{model.page.title}}</h2>
        <p>{{model.page.description}}</p>
      </ol>
    {{/if}}
  </div>
  <div class="pageContent">
    {{component model.page.type
      api=model.api
      page=model.page
    }}
  </div>
</div>

{{ember-notify messageStyle='bootstrap'}}

Nav JS:

import Ember from 'ember';
import util from '../utils/utilities';

export default Ember.Component.extend({
  model: null,
  showHelpModal: false,

  helpURL: Ember.computed('model', function() {
    return util.apiURL('pages/' + this.get('model').api + '/help');
  }),

  didInsertElement: function() {
    let _this = this;
    this.$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
      event.preventDefault();
      event.stopPropagation();
      _this.$(this).parent().siblings().removeClass('open');
      _this.$(this).parent().toggleClass('open');
    });
  },

  actions: {
    openHelp: function() {
      this.set('showHelpModal',true);
    }
  },
});

Nav HBS:

<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="">NexOSS</a>
    </div>

    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        {{#each model.navigation as |item|}}
          <li class="{{if item.active 'active'}}">
            <a href="{{item.link}}" class="dropdown-toggle" data-toggle="dropdown">{{item.title}} <b class="caret"></b></a>
            <ul class="dropdown-menu multi-level">
              {{partial "navbar-dropdown"}}
            </ul>
          </li>
        {{/each}}
      </ul>
      <ul class="nav navbar-nav navbar-right">
        {{#if model.page.help}}
          <li><a href="#" {{action "openHelp"}}>Help</a></li>
        {{/if}}
        <li><a href="editor/{{model.page.link}}">Edit</a></li>
      </ul>
    </div>

  </div>
</nav>

<div id="helpModal">
  {{#bs-modal title="Help" open=showHelpModal body=false footer=false size="lg"}}
    {{#bs-modal-body}}
      {{pdf-viewer
        src=helpURL
        height=600
      }}
    {{/bs-modal-body}}
    {{#bs-modal-footer as |footer|}}
      {{#bs-button type="warning" icon="glyphicon glyphicon-remove" action=(action "close" target=footer)}}
        Close
      {{/bs-button}}
    {{/bs-modal-footer}}
  {{/bs-modal}}
</div>

For more details see repo if necessary but I tried to include everything needed. Repo: http://ift.tt/1RpZBza




Per-Model Promise status on Ember.js loading template

I have an Ember.js (2.3) SPA. In a parent route for a part of the application, I'm loading quite a bit of data (~3.5MB) over many different Model types:

App.ParentRoute = Ember.Route.extend
  model: ->
    Ember.RSVP.hash
      foos: @store.findAll "foo"
      bars: @store.findAll "bar"
      bazes: @store.findAll "baz"
      quxes: @store.findAll "qux"

What I'd like to do is augment my existing parent loading template (currently just a spinner .gif) with information on the status of each of these promises. So when the template first renders it shows each model type:

[ ] Loading Foos...
[ ] Loading Bars...
[ ] Loading Bazes...
[ ] Loading Quxes...

and then as each Promise in the RSVP.Hash resolves, it's shown as an indicator of progress:

[ ] Loading Foos...
[X] Loaded 16 Bars
[ ] Loading Bazes...
[X] Loaded 213 Quxes

I see documentation for a Route loading action but it's using a controller and the documentation seems to indicate that controllers being deprecated (I haven't used any controllers yet in the project).

How do I access Promise state from a model() within the loading template?




Can I get {{link-to}} to specify which animation to use with ember fire?

I have left/right arrows on a page and I want to pick the animation without having to define a relationship between all the routes. Is it possible to set it on the {{link-to}}? Right now it's pretty brittle.




Ember Component cleanup code

just imagine there are more components rendered in web page, and when i click a link, i route to home page, which fills the entire page. (means all components gone in UI)

What are all the things i should make sure to clean up to avoid memory leaks?

Few examples:

If i used Ember.addObserver in component's didInsertElement, i should remove it using Ember.removeObserver in willDestroyElement method.

And any event handlers attached should be detached.

Can i get some more examples / link to see what are all the things i should cleanup and where?




JavaScript - Open a file from localdisk

I am new to Javascript. I want to open a file from the localsystem only not from server ,when the user clicks on a single item from a list .So, I dont know how to open a file in javascript.so,can any one help me to figure it out ?




Disable/Enable form submit button with ember validations status

I am adding form validations using "ember-validations" plugin. I am able to do inline validations, but I need to disable/enable button based on the validation status.

Component.js

export default Ember.Component.extend(EmberValidations, {
validations: {
    'model.firstName': {
      presence: true,
      presence: { message: 'Please enter valid first name.' }      
    },
    'model.lastName': {
      presence: true,
      presence: { message: 'Please enter valid last name.' }      
    },
    'model.email': {
      presence: true ,
      presence: { message: 'Please enter valid email name.' }     
    },
    'model.department': {
      presence: true,
      presence: { message: 'Please enter valid department name.' }      
    },
}
});

Template.hbs

<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-3" for="fname">First Name:</label>
<div class="col-sm-8">
    {{validated-input type="text" placeholder="First Name" value=model.firstName errors=errors.model.firstName}}
 </div>
 </div>
<div class="form-group">
<label class="control-label col-sm-3" for="lname">Last Name:</label>
<div class="col-sm-8">
  {{validated-input type="text" placeholder="Last Name" value=model.lastName errors=errors.model.lastName}}
  </div>
 </div>
<div class="form-group">
<label class="control-label col-sm-3" for="email">Email:</label>
<div class="col-sm-8">
   {{validated-input type="email" placeholder="Email" value=model.email errors=errors.model.email}}
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="department">Department:</label>
<div class="col-sm-8">
    {{validated-input type="text" placeholder="Department" value=model.department errors=errors.model.department}}
</div>
</div>
{{#bs-button classNames="table-btn" action=(action "saveAction" model) buttonType="button" type="update"}}Save{{/bs-button}}
</form>

Screenshot

enter image description here

How can I get the total form inputs validation status while using ember validations, so that i can use that flag for disable/enable button?




jeudi 24 mars 2016

Ember 1.13: multiple canvases

There are several canvases. So far I added them directly to the DOM element using d3. Everything works perfectly except one thing: when I add a footer - it overlays the last canvas. How to fix this?

templates/dashboard.hbs

<div class="row">
    {{my-chart canvasesNumber=3}}
</div>
<footer>
    Some info
</footer>

components/my-chart.js

export default Ember.Component.extend({
    ...
    canvasesNumber: null,

    init: function() {
        this._super();
        id = '#' + this.elementId;
        for (i = 0; i < this.canvasesNumber; i++) {
            d3.select(id).append('canvas')
                           .attr({
                               'width': 200,
                               'height': 100,
                           }).style({
                               'position': 'absolute',
                               'z-index': 0,
                               'left': '0px',
                               'top': (100 * i) + 'px'
                           });
        }
    }
});

Thanks




How do I invoke Ember's component helper programmatically?

I have a list of foos:

[
  { name: 'Foo 1' type: 'important' },
  { name: 'Foo 2' type: 'normal' },
  { name: 'Foo 2' type: 'purple' }
]

I want to render that list, but some of them have special handling -- not just a class, but entirely different markup.

My first instinct would be to use the component helper:

{{#each foos as |foo|}}
  {{component (join 'foo-' foo.type) foo=foo}}
{{/each}}

The downside to that is that I must define a component for each type and the server may send me new types that I don't know about. So I'd like to fall back to a basic foo-generic component if the foo-${type} component isn't defined.

To do that, I figured I'd create a helper:

{{#each foos as |foo|}}
  {{foo-entry foo}}
{{/each}}

// app/helpers/foo-entry.js
Ember.Helper.helper(function([ foo ]) {
  // How do I get a container here?

  // And how do I call the component helper here?
});




Relationship must be key/value pair

Getting the following error:

firebase.js:119 Uncaught Error: thunder@model:provider: relationship hasMany('address') must be a key/value map. Example: { "address": { "address_1": true } } instead got: "-KDehK2aAE15KEQXjHC-"

Address Model

export default DS.Model.extend({
  city: DS.attr('string'),
  state: DS.attr('string'),
  street: DS.attr('string'),
  zip: DS.attr('string'),
  provider: DS.belongsTo('provider')
});

Provider Model

export default DS.Model.extend({
  category: DS.attr('string'),
  status: DS.attr('boolean'),
  name: DS.attr('string'),
  description: DS.attr('string'),
  address: DS.hasMany('address', {async: true}),
  phone: DS.attr('string'),
  email: DS.attr()
});

Here is what I have in Firebase

enter image description here




Highchart series event lost in Ember

I attached a click event handler inside my Highcharts options.

  • sendOrderIds is a closure action.
  • i'm using Lauren Tan's Highchart example as a component.

    init() { this.set('chartOptions.plotOptions.series.events.click', (e) => { let orderIds = e.point.orderIds.split(',');
    this.sendOrderIds({ name: 'orderId', value: orderIds });
    } }, click() { console.log('Ember click handler'); }

What ends up happening is that for the first click event, Highcharts responds. However after that the Highchart event is lost. I need e.point but can't seem to get it. After i hover off, it seems to reattach.

How do solve this?

thanks in advanced!




Ember app errors with ember-simple-auth before restoring session during livereload

I am working on an app in Ember 1.13.8 with a Rails backend that uses Devise for authentication, and I'm trying to upgrade to ember-simple-auth.

I've followed the upgrade path guide at http://ift.tt/1VKNt0O as closely as I can see. Everything is working as before, except that when I save an update to the code, livereload causes the following error instead of reloading certain pages:

ember.debug.js:24180 Error while processing route: users.index Error: Assertion Failed: You may not pass undefined as id to the store's find method

I notice that the error happens before the authenticator's restore() method gets called.

The property (currentUserId) that causes the error when called from a reloading route is in an extension of the session service (abridged):

import Ember from 'ember';
import SessionService from 'ember-simple-auth/services/session';

export default SessionService.extend({
  session: Ember.inject.service('session'),
  store: Ember.inject.service(),

  currentUserId: Ember.computed( 'session.content.authenticated.user.id', function() {
    var sessionUserId = this.get( 'session.content.authenticated.user.id' );
    if ( !Ember.isEmpty( sessionUserId ) ) {
      return this.get( 'session.content.authenticated.user.id' );
    }
  }).property( 'sessionUserId' ),

});

Console logs show that in the currentUserId property this.get('session.isAuthenticated') is false and that this.get('session.data.authenticated') is {}.

I have included the AuthenticatedRouteMixin in the routes I'm trying this in, and the problem persists.

Here is my custom authenticator:

import Ember from 'ember';
import DeviseAuthenticator from 'ember-simple-auth/authenticators/devise';
import ENV from '../config/environment';
import sha1 from 'npm:sha1';

export default DeviseAuthenticator.extend( {
  session: Ember.inject.service(),

  tokenAttributeName: 'auth_token',
  identificationAttributeName: 'email',
  resourceName: 'user',

  authenticate: function( credentials ) {
    var _this = this;

    this.get( 'session' )
      .set( 'currentUserPassword', sha1( credentials.password ) );
    let promise =  new Ember.RSVP.Promise( function( resolve, reject ) {
      _this.makeRequest( credentials ).then( function( response ) {
        Ember.run( function() {
          resolve( response );
        } );
      }, function(xhr, status, error) {
                var response = xhr.responseText;
                Ember.run(function() {
                    reject(response);
                } );
      } );
    });
      return promise;
  },

  restore: function(data) {
    console.log("Trying to restore; data: ");
    console.log( data );
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  invalidate: function() {
    console.log('invalidate...');
    return Ember.RSVP.resolve();
  },

  makeRequest: function( credentials ) {
    var uuid = "abc123";

    if( typeof( window.device ) !== 'undefined' ) {
      uuid = window.device.uuid;
    }

    return Ember.$.ajax( {
      type: 'POST',
      dataType: 'json',
      url: ENV.apiHost + '/api/v1/users/sign_in',
      data: {
        "user": {
          "email": credentials.identification,
          "password": credentials.password,
        },
        "device": {
          "uuid": uuid
        }
      }
    } );
  },
} );

What changes do I need to make to fix livereload after the upgrade, instead of having to log in again after every code change?




Append emberjs component to dom in route

I'm dynamically creating an ember component with an ember route and need to append this component into the DOM. I do so like this:

createwidget : function (row, column, value, htmlElement) {
                var componentObj = {};
                componentObj.props = {
                                        id: 'selectid', 
                                        content: $this.codes, 
                                        optionValuePath: 'code', 
                                        optionLabelPath: 'value', 
                                        selectedValue: '', 
                                        name: 'selectInputName', 
                                        selectedLabel: '', 
                                        dropdownLabel: 'selectLabel', 
                                        placeholder: 'selectPlaceholder'
                                    };
                componentObj.name = 'jpma-select';
                componentObj.type = 'component';
                var component = $this._createComponent(componentObj);
                component.appendTo($(htmlElement));
            }

createwidget is function that comes from the jqxgrid widget. It allows you to dynamically create elements and add them to a grid cell. _createComponent is one of our custom methods that creates a custom ember component, in this case a select. I get the error: "Assertion Failed: You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead."

If I wrap the component as a jQuery object, like this: $(component).appendTo($(htmlElement));

I get this error: "jpma-analytics-tracker.js:154 TypeError: Cannot read property 'ownerDocument' of undefined(…)"

So what gives? What can I do to make this work? Thanks