samedi 29 avril 2017

how do post to a nested route in emberjs

i have a route at /campaigns/{show} which displays a page with an action button 'join campaign'

i.e. /campaigns/{campaignId}
e.g. /campaigns/campaign-1

/apps/templates/campaigns/show.hbs:

...
 <button type="button" >join campaign</button>
...

/apps/controllers/campaigns/show.js:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    joinCampaign: function() {
      // how to do a JSONAPI RESTful POST to /campaigns/{campaignId}/memberships ?
    }
  }
});

upon clicking the 'join campaign' button i wish to do a JSONAPI Restful POST to a rest service listening for a POST to /campaigns/{campaignId}/memberships

i have created the corresponding nested route in ember

i.e. /campaigns/{campaignId}/memberships
e.g. /campaigns/campaign-1/memberships




Ember index.html asset files don't get appended with hash

I deployed my Ember app to S3 using this tutorial: http://ift.tt/2qr68mo

My asset filenames get appended with a hash, but the index.html still references the original filename with the hash, so it fails to load the assets. After reading around, I believe my index.html file is supposed to get updated with new filenames, but not sure why that is not happening.




Ember active link

I have a route where I want to make a sibling route's link-to's active as well. I have tried using current-when in the link-to, but it's not working for me.

my routes are as follows

//projects
//projects/:project_id
//projects/:project_id/user/:user_id

When I navigate to //projects/:project_id route, the right link is set to active. I want the same link to be active on the //projects/:project_id/users/:user_id route.

My link-to in the parent //projects hbs template is



What am I doing wrong here?




List not resorting when property changes in ember

I have made a little demo app where I have a tweet list and I am changing the number of favorites for a random tweet every 0.3 seconds, and the list is supposed to show the top 3 tweets based on favorites, but I can't get it to resort every time a number of favorites is changed for a tweet.

I have made a demo in jsfiddle with this application(show list has to be pressed to show the list).

In my sorting function I want it to check if favorites has changed for any of tweets

 App.AppModel = Ember.Object.extend({
                topTweets: function(){
                    return this.get('tweets').toArray().sort(function(a, b){
                        console.log("sort");
                        return b.favorites-a.favorites;
                    }).slice(0, 3);
                }.property('tweets.@each.favorites')
            });

This is where I change a random tweets favorites

  setInterval(function(){
                                   var iPosition = _.random(0, numTweets-1);
                                   var iFavorites = _.random(0, 4000);
                                    App.appModel.get('tweets').set(iPosition+'.favorites', iFavorites);
                                    App.appModel.get('tweets').set(iPosition+'.text', iFavorites)
                                }.bind(this),300);

The favorites are changing I'm just wondering why isn't the list resorting.




Ember fastboot works with at http api host but not an https one

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
  host: 'http://ift.tt/2pIZnAl',

  // host: 'http://ift.tt/2qq9ypw'
});

The regular host works, but when I use https I get this error:

Error: The adapter operation was aborted
at EmberError.AdapterError (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-http://ift.tt/2pIYhEO)
at EmberError.ErrorClass (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-http://ift.tt/2qqbMW7)
at ajaxError (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-http://ift.tt/2pIURBP)
at Object.hash.error (/home/nick/the-apothecary-shoppe/portal-ember/tmp/broccoli_merge_trees-output_path-http://ift.tt/2qpVn3K)
at fire (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/jquery-deferred/lib/jquery-callbacks.js:78:30)
at Object.fireWith (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/jquery-deferred/lib/jquery-callbacks.js:188:7)
at Object.fire [as reject] (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/jquery-deferred/lib/jquery-callbacks.js:195:10)
at ClientRequest.onError (/home/nick/the-apothecary-shoppe/portal-ember/node_modules/najax/lib/najax.js:208:9)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:309:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at emitErrorNT (net.js:1281:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)

Any thoughts why? this is seriously befuddling me.




Ember JS - Cannot read property 'save' of undefined

In a nutshell, I have created a record ("claimant") in the model hook of a route, but when I try to get the "claimant" record in the actions handler, Ember says the record doesn't exist. As a result, when I try to save "claimant," Ember tells me that it "Cannot read property 'save' of undefined." My guess it is a problem with my initializer, but I'm stumped as to why.

Any help would be tremendously appreciated. Thanks!

The relevant code is as follows:

models/claimant.js

import attr from 'ember-data/attr';
import DS from 'ember-data';
import { belongsTo } from 'ember-data/relationships';

export default DS.Model.extend({
first_name: attr('string'),
submission: DS.belongsTo('submission', {async: false}),
});

models/submission.js

import DS from 'ember-data';
import { belongsTo } from 'ember-data/relationships';

export default DS.Model.extend({
claimant: belongsTo('claimant', {async: false}), 
});

routes/claimant.js

import Ember from 'ember';

export default Ember.Route.extend({
actions: {
    next: function() {
        let claimant = this.get('claimant');
        claimant.save().then(claimant => {
            this.get('submission').createSubmission({
            claimant: claimant
            });
        });
        this.transitionTo('defendant');
    },
},

model() {
    let claimant = this.get('store').createRecord('claimant', {
        first_name: this.get('first_name'),
        });
    return claimant;
}
});

NOTE: If I instead use let claimant = this.get('controller.model'); the record saves properly, but then the BelongsTo relationship between "submission" and "claimant" doesn't properly set. Not sure why.

initializers/submission-initializer.js

import Ember from 'ember';
const {isNone, isEmpty, merge} = Ember;

let submissionProxy = Ember.ObjectProxy.extend({
_currentSubmission: null,
_store:null,

content: function() {
    let currentSubmission = this.get('_currentSubmission');

    if (isEmpty(currentSubmission)) {
    currentSubmission = this.createSubmission();
    }
     return currentSubmission;
    }.property('_currentSubmission'),

current: Ember.computed.alias('content'),

createSubmission(data = {}) {

    let newSubmission = this.get('_store').createRecord('submission', data);   
    this.set('_currentSubmission', newSubmission);
    return newSubmission;
},
});

export function initialize(application) {
application.register('submission:proxy', submissionProxy, {singleton: true});
application.inject('submission:proxy', '_store', 'service:store');
application.inject('component', 'submission', 'submission:proxy');
application.inject('route', 'submission', 'submission:proxy');
application.inject('controller', 'submission', 'submission:proxy');
};

export default {
name: 'submission-initializer',
after: ['ember-data'],
initialize: initialize
};

templates/claimant.hbs

<h2 id="title">Welcome to the Claimant Page!</h2>

<form>
<div class="form-group">
  <label for="first_name">First Name</label>
  
</div>

<button class="btn btn-primary" >Next</button>
</form>




vendredi 28 avril 2017

How to lookup child elements in ember model?

Here are the two models that i have defined

//Plugin model
import DS from 'ember-data';

export default DS.Model.extend({
  name:    DS.attr('string'),
  account: DS.hasMany('account')
});

//account model
import DS from 'ember-data';

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


// Plugin Route
import Ember from 'ember';

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


//Accounts route
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params){
    return this.store.findRecord('account',params.id);
  }
});

The api structure to list accounts associated with a plugin is /plugins/:id/accounts.The problem is i am unable to make request to the same using above code. params.id in case above is id for plugin and not account. Is there something i am missing out on emberjs or should i change my api to bring accounts to root ?




How to have an Ember route both with and without query params

Currently, I have a route that looks like "abc.com/name?age=4". How do I configure my route, so that "abc.com/name" without the query param, "age=4", is still a valid page?

All my route file has right now is:

model(params) {
    return this.store.queryRecord('name', params);
}




DRF lowercase header key

Is it possible to use lowercase HTTP header key "content-type" with django rest framework parsers?

HTTP headers are case insensitive, but it doesn't seem to work with DRF 3.3.2. My frontend (emberjs) sends request with lowercase header name by ember-network(Fetch API).




Normalize responce JSONAPI with Ember Data

I have an application JSONSerializer, I want to be able to normalize the response as JSONAPI format. I created a normalizeFindRecordResponse but doesn't work when trying to retrieve a record, only works for creating records. My API only accepts JSON format, not JSONAPI.

normalizeFindRecordResponse(store, type, payload) {

        return {
          data: {
            attributes: payload.data.attributes,
            id: payload.data.id,
            links: payload.data.links,
            relationships:{
                paymethods: payload.data.paymethods,
                properties: payload.data.properties,
                transactions: payload.data.transactions
            },
            type: type.modelName,
            included: payload.data.included
          }
        };
    }




How to validate checkbox, selectbox and radiobutton in ember-cp-validations

I am using ember-cp-validation in ember js application for validation. I want to validate checkbox, selectbox and radiobutton.Give any sample approach.




Ember Template Compiler JS plugin not working when pre-compiled in Ember CLI rails appl

I am using ember-template-compiler.js as one of the dependency plugin in EmberCLI Rails application for Ember Handlebar templates . When I am trying to pre-compile the assets I am getting the following issue.

EmberCli::App::BuildError: EmberCLI app "account_settings" has failed to build
TypeError: Cannot read property 'length' of undefined

  at Object.TransFormDotComponentInvocation._isMulipartPath (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:14387:24)

  at Object.TransFormDotComponentInvocation._isInlineInvocation (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:14391:16)

  at traverse.MustacheStatement (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:14416:21)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2753:36)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2791:27)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitArray (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2805:26)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2789:13)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitArray (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2805:26)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2789:13)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitArray (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2805:26)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2789:13)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2791:27)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitArray (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2805:26)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2789:13)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitArray (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2805:26)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2789:13)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at visitArray (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2805:26)

  at visitKey (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2789:13)

  at visitNode (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2767:17)

  at traverse (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:2841:9)

  at Object.TransFormDotComponentInvocation.transform (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:14414:7)

  at Object.preprocess (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:3463:35)

  at precompile (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:1290:34)

  at Object.precompile (<app_folder_rails>/account_settings/bower_components/ember/ember-template-compiler.js:15389:12)

  at Object.module.exports.template (<app_folder_rails>/account_settings/node_modules/ember-cli-htmlbars/utils.js:29:40)

  at TemplateCompiler.processString (<app_folder_rails>/account_settings/node_modules/ember-cli-htmlbars/index.js:68:36)

  at Promise.then.result.output (<app_folder_rails>/account_settings/node_modules/broccoli-persistent-filter/lib/strategies/persistent.js:41:23)

  at initializePromise (<app_folder_rails>/account_settings/node_modules/rsvp/dist/rsvp.js:589:5)

  at new Promise$1 (<app_folder_rails>/account_settings/node_modules/rsvp/dist/rsvp.js:1077:33)

  at <app_folder_rails>/account_settings/node_modules/broccoli-persistent-filter/lib/strategies/persistent.js:40:18

  at tryCatch (<app_folder_rails>/account_settings/node_modules/rsvp/dist/rsvp.js:539:12)

  at invokeCallback (<app_folder_rails>/account_settings/node_modules/rsvp/dist/rsvp.js:554:13)

  at publish (<app_folder_rails>/account_settings/node_modules/rsvp/dist/rsvp.js:522:7)

  at flush (<app_folder_rails>/account_settings/node_modules/rsvp/dist/rsvp.js:2414:5)

  at _combinedTickCallback (internal/process/next_tick.js:67:7)

  at process._tickCallback (internal/process/next_tick.js:98:9)
Tasks: TOP => assets:precompile => ember:compile

Previously it had worked well. I am using the following node and ember versions.

ember-cli: 2.7.0
node: 6.2.1
os: linux ia32
Ruby: 2.3.1
Rails: 4.2.1
npm: 3.9.3
OS: Ubuntu 16.04

Also Please check bower.json , package.json file data as follows

bower.json:
{
  "name": "account-settings",
  "dependencies": {
    "ember": "^2.0",
    "ember-cli-shims": "0.0.6",
    "ember-cli-test-loader": "0.2.1",
    "ember-data": "^2.0",
    "ember-load-initializers": "0.1.7",
    "ember-qunit": "0.4.16",
    "ember-qunit-notifications": "0.1.0",
    "ember-resolver": "~0.1.20",
    "jquery": "^1.11.3",
    "loader.js": "ember-cli/loader.js#3.4.0",
    "qunit": "~1.20.0"
  }
}

And

   package.json:
    {
      "name": "account-settings",
      "version": "0.0.0",
      "description": "Small description for account-settings goes here",
      "private": true,
      "directories": {
        "doc": "doc",
        "test": "tests"
      },
      "scripts": {
        "build": "ember build",
        "start": "ember server",
        "test": "ember test"
      },
      "repository": "",
      "engines": {
        "node": ">= 0.10.0"
      },
      "author": "",
      "license": "MIT",
      "devDependencies": {
        "active-model-adapter": "2.0.3",
        "broccoli-asset-rev": "^2.2.0",
        "ember-cli": "1.13.13",
        "ember-cli-app-version": "^1.0.0",
        "ember-cli-babel": "^5.1.5",
        "ember-cli-coffeescript": "1.13.2",
        "ember-cli-content-security-policy": "0.4.0",
        "ember-cli-dependency-checker": "^1.1.0",
        "ember-cli-emblem": "0.3.1",
        "ember-cli-htmlbars": "^1.0.1",
        "ember-cli-htmlbars-inline-precompile": "^0.3.1",
        "ember-cli-ic-ajax": "0.2.4",
        "ember-cli-inject-live-reload": "^1.3.1",
        "ember-cli-qunit": "^1.0.4",
        "ember-cli-rails-addon": "0.0.13",
        "ember-cli-release": "0.2.8",
        "ember-cli-sri": "^1.2.0",
        "ember-cli-uglify": "^1.2.0",
        "ember-data": "1.13.15",
        "ember-disable-proxy-controllers": "^1.0.1",
        "ember-export-application-global": "^1.0.4",
        "ember-radio-button": "1.0.7",
        "emberx-select": "2.0.2",
        "phantomjs": "^2.1.3"
      }
    }

Can you please check with this. Solution for this will help me a lot.




jeudi 27 avril 2017

Can't model in the view in emberjs

I am just getting started with ember... I managed to save the data to firebase but can't get it to the client, this is my code:

Route:

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

template:


    <h2> </h2>


modeljs:

import DS from 'ember-data';

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

});

I did manage to save an item to firebase with a form on my website so the model is sending data to firebase but I am not sure how to get it back to the view?




How to validate ember-power-select using jquery validation?

I have a power-select that I want to validate. When user presses submit, I want them to have selected from the power-select dropdown. If they have not selected from the dropdown, then it would show a warning. I am using ember-power-select for dropdown and jquery-validation for validation.

Below is what my ember template (component) has - I included a text input (amount) that works:

//emblem.js

form id="salesForm"
    .form-group
      label Account Name (Organization)
      = power-select options=organizations selected=sale.organization searchField="name" onchange=(action "organizationChanged" ) placeholder="Account Name" required="required" name="organization" id="organization" as |organization|
        = organization.name

    .form-group
      label Amount
      = input type="text" value=sale.amount placeholder="Amount" class="form-control" required="required" name="amount" id="amount"
    ...

Inside my component.js:

  didRender(){
    ...
    var validator = this.$('#salesForm').validate({
      rules: {
        organization: {
          required: true
        },
        amount: {
          required: true
        }
      },
      messages: {
        organization: {
          required: "Please select an organization"
        },
        amount: {
          required: 'Please enter amount number'
        }
      },
      errorPlacement: function(error, element){
        error.insertAfter(element);
      }
    });
    ...
  }

Currently, if I don't select anything, it shows error under amount, but it does not show anything under organization. I noticed that when I inspected power-select, it has a fixed power-select id. Both my required='required' andname='organization` lines were not shown either.

ember-power-select-inspect

Compare that with Amount, where it has the specified name, id, and required. I think this is the reason why, but I am not 100% sure.

amount input text inspect

In short, how can I enable basic validation on ember-power-select so it shows error message when user does not select from dropdown?




Is it possible to reload the router in a running ember.js app in order to update the path strings of routes?

I'm implementing multi-language support in my app, and I guess this is the last thing that I would need in order to be able to change between languages without reloading the whole app/page. (I already have a solution with full page reload.)

For a simple example let's say this is how my router looks:

Router.map(function() {
  this.route('search', { path: t('search') });
  this.route('item', { path: `${t('item')}/:id`);
});

The t function would be getting the correct translation for the given strings in the currently active language.

The structure of the route hierarchy won't change, the only things that need to be updated are the path strings. Application state should be kept, of course.

I'm wondering whether this is possible to do.




Ember acceptance test multiple keypress event

I want to simulate multiple keypress(ctrl+alt, alt+enter, alt+uparrow etc) events for my acceptance test cases.

Ember test documentation has given an abstract syntax for the triggerEvent method. It's still unclear how to use it for multiple keypress events simulation.

Please help!




Image slider in ember

I am using "ember-cli-slick": "2.0.0" And in handlebars I am using this component -


    
        <img src="">
    


When i am inspect elements i can see images with width 1px and height 0px.

Can anyone have any idea?




mercredi 26 avril 2017

Ember-CLI: Ember Build keeps building the wrong index.html

Ideally, I want my index.html from this:

<!-- app/index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Program With Erik Blog Example</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    

    <link rel="stylesheet" href="assets/vendor.css">
    <link rel="stylesheet" href="assets/example1.css">

    
  </head>
  <body>
    

    <script src="assets/vendor.js"></script>
    <script src="assets/example1.js"></script>

    
  </body>
</html>

into production code. But for some strange reason, each time I call ember build, I do not get the expected production-looking code. Instead I get something like this

I'm am new to deploying ember apps with firebase. I have been fiddling around a lot with my config/environment.js file and my firebase.json file mostly.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Welcome to Firebase Hosting</title>
    .
    .
    .
    <!-- lots of code -->

It's the default firebase page!

Firebase welcome page

What is happening? I've deleted the picture multiple times. But each time I call ember build it builds the firebase default page rather than my ember app index.html.

I'm new to ember and I've been fiddling around heavily with the config/environment.js and the firebase.js. Any thoughts on why this might be happening?




How to use jquery-validation on emberjs properly?

I am trying to create a simple validation to require name (will add more validations later). The app an ember app, and we want to use jquery validation.

I am having trouble just to get a basic validation running. This is what I have:

//index.html
<script src="http://ift.tt/1oMJErh"></script>
<script src="http://ift.tt/2qfU6MO"></script>

... 
//body and such//
...

<script>
  $('#salesForm').validate();
</script>

</body>

Inside a component, say sales-form:

//app/components/sales-form/template.emblem

form id="salesForm"
  ...
  .form-group
    label Some Sales Info
      = input type="text" disabled=false value=salesNumber placeholder="Sales Number" class="form-control" required

  button{action: 'clickNSave'}
  ...

This gives me a build error, because emblem does not recognize required on the input.

How can I create a simple validation using jquery-validation on ember app that uses emblem for template?

Additional question, is my validation on index.html correct, to run the validation at the very end, right before closing body tag? If not, where is the best way to insert $('#someForm').validate();?




EmberJS how to solve `Could not find module` when using linked addons

I have a main EmberJS app (AppA) (with routes, models, services...).

Now I would like to create a second app (AppB) which use these models, services ...

On AppA I added the following lines to app/app.js:

engines: {
  appB: {
    dependencies: {
      services: [
        'store'
      ]
    }
  }
}

And in package.json:

  "keywords": [
    "ember-addon"
  ]

I also created the following index.js

/*globals module */

module.exports = {
  name: 'app-a',

  treeForPublic: function(tree) {
    // Return tree as is. This prevents ember-cli from moving the tree to /common.
    return tree;
  },

  // We always want this to be true so that addon files are watched.
  isDevelopingAddon: function() {
    return true;
  }
};

On the AppB side I ran npm link ../app-a and add "app-a": "*" to package.json.

I'm now able to run this.get('store').findAll('product') in a controller of AppB when the model is defined in AppA.

However the model product has a dependency to underscore which is working fine in the AppA app.

But on AppB I'm getting the following javascript error Error: Could not find module underscore imported from app-b/services/store.

Any idea what I'm doing wrong?

I was inspired by http://ift.tt/2pAduYv.




How to access window.location in environment.js

In my development setup i use local network resources. So i have to adapt some environment urls depending on my network (home / work) like this:

ENV.APP.image_path = home ? 'http://home.server' : "http://work.server"; 

Is it possible to use window.location in config/environment.js to change this urls automatically?




mardi 25 avril 2017

Class of type Blob being converted to Object in Emberjs, Electron and PouchDB/CouchDB Project

i seem to be having a funny issue here. I am currently developing an offline first web application with emberjs and a desktop application wrapped in electron. Both are running off a pouchdb replicating with couchdb. I noticed images uploaded on the web are only accessible there while images uploaded from the desktop app are only accessible there too. The uploaded Blob class is only seen as blob within the environment where it was uploaded. Please i really need a pointer here

When i access the image in a different environment this is what i see

content_type:"image/jpeg"
data:Object
digest:undefined
length:undefined
name:"photo_record_1.jpg"
stub:undefined
__ember1493143170849:"ember775"
__ember_meta__:Meta
__proto__:Class

When it should be

__ember1493143512170:"ember788"
__ember_meta__:Meta
content_type:"image/jpeg"
data:Blob
digest:undefined
length:undefined
name:"photo_record_1.jpg"
stub:undefined
__proto__:Class




Ember model finding records

I'm having trouble getting Ember's queryRecord to work properly. I'm trying to grab a site config from the server.

//app/routes/application.js

model: function(){
    var self = this;

   var config = this.get('store').queryRecord('config',{}).then(function(config) {
    console.log(config.get('appname'));
  });
}

//app/adapters/config.js

import DS from "ember-data";
import ENV from './../config/environment';

export default DS.Adapter.extend({
  queryRecord(modelName, query) {
      return Ember.$.getJSON( ENV.APP.apiFull + 'config' );
  }
});

//JSON returning from server AJAX call

{"config":{"id":1,"environment": "development", "appname":"Sample App Name"}}

The console.log statement in //app/routes/application is returning undefined. This all seems to match up with the Ember documentation for version 2.9. What am I doing incorrectly?




how to write a unit test for controller action with promises in emberjs

I have a ember js controller with the following action that takes a model. How do I write a unit test to test the action which returns a promise? deleteUser(model) { model.destroyRecord().then(() => this.transitionToRoute('posts')); }




Catch a value from promise [duplicate]

This question already has an answer here:

I am currently working with an imdb-api which returns values with a promise. I am working with Ember and I don't know how to catch that variable to send it to the template.

import Ember from 'ember'
import imdb  from 'npm:imdb-api'

exports default Ember.Route.extend({
   model(params){
      this.movies = [];
      let search = Ember.get(params, 'search');
      imdb.get({name: search}).then(function(movies){
         //how can I do to change the value of this.movie 
         //this.movies= movies won't work because it's in a different scope
      })
   }
})




Ember.js Best Practices - Can/Should I override sendAction?

In my Ember App, I have a large number of modal dialog components that I render in my Application route like so:



All dialog components extend from a single base class, where, for convenience, I have overridden sendAction. The point of the override is to always trigger some action on the target, as opposed to sendAction's default behavior of "if the property is undefined, do nothing". Here is what that looks like:

sendAction: function (actionName) {
  if (Em.isEmpty(this.get(actionName))) {
    this.set(actionName, actionName);
  }
  this._super(...arguments);
},

This seems to work as I would expect: always triggering an action on the target that will then bubble up the stack. What I'm wondering is...

Are there any implications/side-effects of overriding sendAction that I am not aware of?




Ember js big table

I have a page with a few tables, in total there are a few after 1000 rows.

After the tables is ready, when I click to go on another page, the route is changing in the address bar, but nothing happens until a few seconds. Then the new page is rendered.

Why is that and what can I do?




Using autoNumeric 4.x with Emberjs

I am currently using autoNumeric 1.9.46 in one of my ember projects. I installed it as a bower dependency; since it is a jQuery plugin and added

app.import(`bower_components/autoNumeric/autoNumeric.js`);

to ember-cli-build.js file and it is all good. I can use it as described in documentation as $(selector).autoNumeric().

Now I decided to use autoNumeric v4.0.0-beta.14; but it seems to be ES6 module now. I tried to install it through npm install autonumeric and import it via import AutoNumeric from "AutoNumeric" but I got "Could not find module AutoNumeric imported from ..." error. I tried to install it through ember-browserify as described in here and import it as import AutoNumeric from 'npm:AutoNumeric' and still the same error. Can somebody help me in using autoNumeric v4.0.0-beta.14, which is now an ES6 module? I am open to any help in directing using custom ES6 modules with Emberjs as well. Thanks.




validate() is not a function in ember-cp-validation

I am using ember-cp-validation in ember js application for validation. using validate() method in components page. but i am getting error(validate is not a function). I referred this link

In models page,

import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
    name: validator('presence', true),

    address:[
        validator('presence', true),
        validator('length', { max: 300}),
    ],

    pincode: validator('presence', true),

    email:[
        validator('presence', true),
        validator('format', {type:'email'})
    ]

});

export default DS.Model.extend(Validations,{
    name: DS.attr('string'),
    address: DS.attr('string'),
    pincode: DS.attr('number'),
    email: DS.attr('string')
});

And Components page,

import Ember from 'ember';

export default Ember.Component.extend({     
    actions: {
        authenticate() {            
            let profile = this.get('profile');
            profile.validate().then(({ validations }) => {
                if(validations.get('isValid')){
                    this.transitionToRoute("welcome");
                }
            });         
        }
    }
});




Model getting a URL as a resource in ember-data

I have a model that gets a URL as a source of data, currently an array of other models. I want to map it as a store and thus I created a model that acts as an intermediate.

This is the schema:

app/models/user_info.js

export default DS.Model.extend({
....
studies: DS.belongsTo('studies-collection-id);
....

app/models/studies-collection-id.js

export default DS.Model.extend({
  studies: DS.hasMany('study')
});

app/adapters/studies-collection-id.js

export default ApplicationAdapter.extend({
  urlForFindRecord (id, modelName, snapshot) {
    return(id);
  }
});

This works fine and I get the request that I need fired and the server responds with the array of studies that I was expecting. The problem is I can't get those studies to reach the store in any way.

I tried serialising the response but currently have no success on that. I post what I'm using now:

/app/serializers/studies-collection-id.js

import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({
  primaryKey: 'self',
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    let jsonApiStudiesArray = [];
    jsonApiStudiesArray['data'] = payload.slice(0);
    jsonApiStudiesArray['self'] = id;
    jsonApiStudiesArray['type'] = primaryModelClass.modelName;
    jsonApiStudiesArray['data'] = [];
    jsonApiStudiesArray['data']['attributes'] = payload.slice(0).map(function(item){
      let returnArray = [];
      returnArray['type'] = 'study';
      returnArray['self'] = item['self'];
      returnArray['attributes'] = item;
      return(returnArray);
    });
    return this._super(store, primaryModelClass, jsonApiStudiesArray, id, requestType);
  }
});

Anyone has a suggestion on this?. I feel like I'm trying to hack ember on this and it should be easier. Thank you very much for your help




Filemanager component for ember cli

I need to implement file management functionality and tried to find some addon to reuse it but unfortuanlelly have found nothing for ember.

Is there some addon for ember like angular-filemanager or any file management addon?

thanks




How to get week numbers of current month in moment.js

I want to get the week numbers of a particular month eg: January 2017 ,the weeknumbers in this months are [52,1,2,3,4,5] So how to get the above in an array? Thanks




lundi 24 avril 2017

Install ember flora editor in docker

i'm currently working on an existing ember project with rails as a backend and docker is used as a container.

I have to implement a WYSIWYG Editor in an ember view and opting for ember flora editor (http://ift.tt/23ZRsYc). However, i'm facing issues while installing it. Firstly i tired installing the add-on using ember install ember-froala-editor but got the following error logs:

Could not find watchman, falling back to NodeWatcher for file system events
The `install` command does not take any arguments. You must use `install:npm` or `install:bower` to install a specific package.

I searched for it and got an answer saying that i should try something like ember install:addon ember-froala-editor.

This gives me the following logs

(node:5256) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
(node:5256) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
version: 0.1.12
Could not find watchman, falling back to NodeWatcher for file system events
(node:5256) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
Installed packages for tooling via npm.
Cannot read property 'apply' of undefined

TypeError: Cannot read property 'apply' of undefined

  at Class.init (/Users/c224/Documents/sites/path/node_modules/ember-froala-editor/index.js:33:21)
  at new Class (/Users/c224/Documents/sites/path/node_modules/ember-cli/node_modules/core-object/core-object.js:18:12)
  at /Users/c224/Documents/sites/path/node_modules/ember-cli/lib/models/project.js:368:27
  at visit (/Users/c224/Documents/sites/path/node_modules/ember-cli/lib/utilities/DAG.js:23:3)
  at DAG.topsort (/Users/c224/Documents/sites/path/node_modules/ember-cli/lib/utilities/DAG.js:82:7)
  at Project.initializeAddons (/Users/c224/Documents/sites/path/node_modules/ember-cli/lib/models/project.js:364:9)
  at Project.reloadAddons (/Users/c224/Documents/sites/path/node_modules/ember-cli/lib/models/project.js:501:15)
  at Class.<anonymous> (/Users/c224/Documents/sites/path/node_modules/ember-cli/lib/tasks/addon-install.js:40:27)
  at $$$internal$$tryCatch (/Users/c224/Documents/sites/path/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:490:16)
  at $$$internal$$invokeCallback (/Users/c224/Documents/sites/path/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:502:17)
  at $$$internal$$publish (/Users/c224/Documents/sites/path/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:473:11)
  at $$rsvp$asap$$flush (/Users/c224/Documents/sites/path/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1581:9)
  at _combinedTickCallback (internal/process/next_tick.js:67:7)
  at process._tickCallback (internal/process/next_tick.js:98:9)

I am not much aware about docker and hence on searching found this one command $ docker-compose run --rm ember generate model userhere. However i'm not sure if this will help.

Please guide me as to what exactly needs to be done to install this editor successfully to the ember app.

Please let me know if any other logs are needed. Thanks in Advance.




Model instance not sent via link-to to dynamic route if using RSVP.hash()

I can't seem to pass a model instance to a dynamic route if the dynamic route is model hash.

I have a companies route:

// routes/companies,js
export default Ember.Route.extend({
  model() {
    return this.get('store').findAll('company');
  }
});

And a companies/edit route:

// routes/companies/edit.js
export default Ember.Route.extend({
  model(params) {
    var store = this.store;
    return Ember.RSVP.hash({
      companies: store.findRecord('company', params.company_id),
      companyTypes: store.findAll('companyType')
    });
  }
});

My companies template is:

<!-- templates/companies.hbs -->
<div style="width:400px; height: 300px; overflow:true;float:left;">
  <h2>Companies</h2>

  
    <p>
      
      Edit
    </p>
  
  New
</div>


If I go directly to the dynamic route, all works fine.

However, in the link-to in companies.hbs I am passing the company model to the companies.edit route, but the data never gets to the companies.edit (company is undefined) I assume because companies.edit is expecting the model hash.




dimanche 23 avril 2017

Object mock using data factory guy addon

I am new to Embebr js and using ember-data-factory addon to mock ajax response however having trouble mocking below response.

 {
      "employee/profile": {
        "id": 60799,
        "gender": "Male",
        "fname": "Mick",
        "lname": "Hussey",
        "addresses": [
          "50345"      
        ]   
      },
      "employee/addresses": [
        {
          "id": "50345",
          "addressState": "GA",
          "zip": "30004"  
        }     
      ] 

    } 

To achieve this i have created both profile and address model in tests/factories/ directory. employee/profile Model

import FactoryGuy from 'ember-data-factory-guy';

FactoryGuy.define('employee/profile', {
  default: {    
    id: 60799,
    gender: 'Male',
    fname: 'Mick',
    lname: 'Hussey',
    addresses:  FactoryGuy.hasMany('employee/addresses')  
  } 
});

Address Model:

import FactoryGuy from 'ember-data-factory-guy';

FactoryGuy.define('employee/address', {
  default: {   
    id: '50345',
    addressState: 'GA',
    zip: '300014'   
    customer: FactoryGuy.belongsTo('employee/profile'),

  }
});

And when i try to build profile object using below code snippet, all the fields except addresses is getting populated.

let profile = this.build('customer/profile');

can anybody please help me understand whats going wrong.

Thanks Gautam




tabs dynamic component waiting before switching to next tab

I'm using the custom tabs config but seem to have a problem loading dynamic content (components within tab panes).

The component loads promise/s or does some processing on init, and when switching to a new tab it will not switch immediately but wait until the component finishes initialization.

ie:



    
        <a href="#edit" role="tab" >Edit</a>

     

    
       
          <h2>TEST</h2>//->this does not show until some-component finishes initialization

          //->does some processing, promises or whatever on init
      
    



I tried manually setting and keeping track of the activeId by hooking into the onChange event but have the same effect.




Illegal Operation on a Directory with Unknown Broccoli Plugin

Output from ember version --verbose && npm --version:

ember-cli: 2.12.1
http_parser: 2.7.0
node: 6.10.2
v8: 5.1.281.98
uv: 1.9.1
zlib: 1.2.11
ares: 1.10.1-DEV
icu: 58.2
modules: 48
openssl: 1.0.2k
os: darwin x64
3.10.10

When I try ember s I have the following error,

Livereload server on http://localhost:49153
Serving on http://localhost:4200/
The Broccoli Plugin: [object Object] failed with:
Error: EISDIR: illegal operation on a directory, read
    at Error (native)
    at Object.fs.readSync (fs.js:732:19)
    at tryReadSync (fs.js:487:20)
    at Object.fs.readFileSync (fs.js:535:19)
    at /Users/li-xinyang/Desktop/XX_MemoCycle_Firebase/node_modules/broccoli-flatiron/index.js:33:16
    at Array.forEach (native)
    at readDirectory (/Users/li-xinyang/Desktop/XX_MemoCycle_Firebase/node_modules/broccoli-flatiron/index.js:28:31)
    at /Users/li-xinyang/Desktop/XX_MemoCycle_Firebase/node_modules/broccoli-flatiron/index.js:21:15
    at tryCatch (/Users/li-xinyang/Desktop/XX_MemoCycle_Firebase/node_modules/rsvp/dist/rsvp.js:539:12)
    at invokeCallback (/Users/li-xinyang/Desktop/XX_MemoCycle_Firebase/node_modules/rsvp/dist/rsvp.js:554:13)

The broccoli plugin was instantiated at:
undefined

Below is a list of devDependencies,

package.json File


{
  "name": "memo-cycle",
  "version": "0.0.0",
  "description": "A study tool for serious learner",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^2.4.1",
    "ember-cli": "2.12.1",
    "ember-cli-app-version": "^2.0.0",
    "ember-cli-babel": "^5.1.7",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-eslint": "^3.0.0",
    "ember-cli-gravatar": "^3.8.1",
    "ember-cli-htmlbars": "^1.1.1",
    "ember-cli-htmlbars-inline-precompile": "^0.3.6",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-qunit": "^3.1.0",
    "ember-cli-sass": "^6.1.2",
    "ember-cli-shims": "^1.0.2",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-export-application-global": "^1.0.5",
    "ember-in-viewport": "^2.1.1",
    "ember-inline-svg": "^0.1.10",
    "ember-load-initializers": "^0.6.0",
    "ember-paper": "^1.0.0-alpha.19",
    "ember-power-select": "^1.6.1",
    "ember-power-select-with-create": "^0.3.1",
    "ember-resolver": "^2.0.3",
    "ember-route-action-helper": "^2.0.2",
    "ember-simple-auth": "^1.2.2",
    "ember-source": "~2.12.0",
    "loader.js": "^4.2.3"
  },
  "engines": {
    "node": ">= 4"
  },
  "private": true
}


It was working fine before my last to commit. What I have done in the last two commits are I remove all .DS_Store files in the last commit and added Firebase deploy config files and install cloud function dependencies via Yarn in the last second commit.

What I have tried to resolve the issues, but the issue persists.

1) Delete all node modules via rm -rf node_modules and re-install them npm install (dependencies were installed via Yarn)

2) Remove the project and clone from the origin

3) Revert back to early commit (issue persists even I revert back to the initial commit and re-install all the dependencies of course)

4) Restart Mac 😅

5) Update .ember-cli file

.ember-cli File


{
  /**
    Ember CLI sends analytics information by default. The data is completely
    anonymous, but there are times when you might want to disable this behavior.

    Setting `disableAnalytics` to true will prevent any data from being sent.
  */
  "disableAnalytics": false,
  "liveReload" : true,
  "environment" : "mock-development"
}





ember: cannot access model from service

I am working on a cart service that will be injected, and I am using ember-data to store the cart data (because I need to persist the cart to the back-end).

Naturally, within the service I need to create computed properties on the cart data so that I can provide sums of quantities and totals.

But I am having a really, really hard time accessing the 'cart' model from the store in order to do this. Here's what I am trying to do:

export default Service.extend({

    store: inject.service(),

    cartObj: null, // set in init() so cart data can be used in computed properties

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

        // get cart model from store, set it to property on the service
        let cartObj = this.get('store').peekAll('cart').get('firstObject');
        set(this, 'cartObj', cartObj);
    },

    lineItems: computed('cartObj.cartitems.[]', function() {
        // cartitems is a collection stored in each cart object
        return get(this, 'cartObj.cartitems');
    }),
    total: computed.sum('itemPrices'), // cart total

...

No matter what I try in init(): this.get('store').peekAll('cart').get('firstObject') or this.store.peekAll('cart').get('firstObject') or variations of the same with .objectAt(0) ...nothing works.

I either get errors about "get" not being a function, or the cartObj assignment evaluates to null

EVEN THOUGH the model is there, with data in it:

enter image description here

What am I missing here?




Binding ember model in dynamically generated form

I am learning ember js from last couple of weeks, and building an application to learn it. I am in a situation where I have to build a dynamic form which will be bind to ember model. (the simplest example for this problem could be nested form, where we can click on add more link/button to add form on the fly, and add values to them).

But for me, I am building survey like site, where we can have lots of option to select and user can select one of the option from available one:

what I have done so far?

readAnswer: Ember.computed(function() {
    return this.get('store').query('answer', { filter:
      {
        question_id: this.get('question.id'),
        submission_id: this.get('submission.id')
      }
    })
  }),

  buildAnswer: Ember.computed(function() {
    this.get('store').createRecord('answer', {
      question: this.get('question'),
      submission: this.get('submission')
    })
  }),

  answer: Ember.computed(function() {
    const ans = this.get('readAnswer');
    console.log(`question_id: ${this.get('question.id')}, submission_id:     ${this.get('submission.id')}`);
    if(Ember.isEmpty(ans)) {
      return this.get('buildAnswer');
    } else {
      return ans;
    }
  })

answer.hbs

<div class="row col-sm-12">
  <div class="form-group">
    <label></label>
    <p>
      
    </p>
    <p>
      
    </p>
  </div>
</div>

NOTE here answer.hbs is a component, and these are call recursively (in loop) from parent route. So for 2 questions, we can have 4 textboxes, 2 text box for each question, first textbox for answer.field01 and second textbox for answer.field02

Let's say I have 2 questions, till now, I can see 2 answers build in the ember store if they don't already exists in database and then, I can see 4 textboxes generated in view. But they are not binding. Meaning, if I can value of the textbox, nothing happens in the ember store.

Expected Result

When I input answer in the textbox, it should bind with answer.fieldxx properly.




How to update an ember-infinity infinityModel?

I am trying to implement searching with ember-infinity. But, I do not understand the interaction between the route model and infinityModel.

I have the following code:

model() {
  ...
  return this.infinityModel("myModel", {...}, {...})
}

My search action looks like the following:

search(searchCriteria){
  const _this = this;
  ...
  _this.infinityModel("myModel", {search:searchCriteria, ...}, {...}).then((myMod)=>{
    ...
    _this.controller.set('model', myModel);
  }); 
}

So this works, but the my query gets fired twice when search is called.

The following only fires the query once.

search(searchCriteria){
  const _this = this;
  ...
  _this.infinityModel("myModel", {search:searchCriteria, ...}, {...}); 
}

But my model does not update. However infinityModelUpdated() function is fired. So I assume that means the infiniteModel was updated, which I assume is my model.

I am pretty sure I am missing something simple. But any help would be greatly appreciated.




How can I extend DS.Store in an Ember Application?

I want to add a function to the store as part of a web sockets plugins I am working on.

As part of this, I need to extend the store (DS.Store).

I have tried putting the following file in both app/store.js & app/stores/application.js but this does not seem to work.

import DS from 'ember-data';

export default DS.Store.extend({
  init: function() {
    console.log('Using custom store!');
    return this._super.apply(this, arguments);
  }
});

Do I need to put this somewhere else?




samedi 22 avril 2017

ember: modeling a shopping cart in ember-data

I'm struggling with getting my head around modeling a shopping cart that needs to persist to the back-end. I think I understand the relationships, and how to retrieve data that's in the model...it's how to actually add the data that's tripping me up.

I've got two pretty simple models:

The cart:

export default DS.Model.extend({
    cartitems: hasMany('cartitem')
});

The cart items

export default DS.Model.extend({
    product: belongsTo('product', { async: true }),
    cart: belongsTo('cart'),

    variantCodes: attr(''),
    quantity: attr('number'),
    itemPrice: attr('number'),
    itemOrigPrice: attr('number')

});

I created a cart service that contains properties, computed properties and methods. In this cart service is where I'm having the trouble, starting with my add method:

...

add(item) {
    this.get('store').findRecord('cart', get(this, 'cartId')).then(result => {
        cart.get('cartitems').addObject(this.get('store').createRecord('cartitem', {
                id: item.skuid,
                variantCodes: item.variantCodes,
                quantity: item.quantity,
                itemPrice: item.itemPrice
            })
        );
        cart.save();
    });
}

That kind of works...it shows the cart and cartitem models (with data and relationsips) in the ember inspector, but doesn't send a payload for the cart items to the API. I'm thinking it's because I have to do a save for each cartitem.

But this rig also seems overly complex and I think would result in a bunch of network requests. Is this even the right approach?

I think the DS.EmbeddedRecordsMixin would help here, but I have no idea how that would look. I can't seem to find any examples of it in use for POSTing to the API. Only for retrieving. Any help appreciated!




ember: TypeError: Cannot read property 'set' of undefined

I am trying set a value into userSessionStorage, when i am accessing it from the authenticate() function it seems to work correctly.

However, it is not working in the .then() promise.

app/controllers/show.js

import Ember from 'ember';
import { storageFor } from 'ember-local-storage';

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

  userSessionStorage: storageFor('user'),

  authenticator: 'authenticator:custom',

  actions: {
    authenticate: function() {
      var credentials = this.getProperties('identification', 'password');
      // ok
      this.set('userSessionStorage.username', credentials.identification);

      this.get('session').authenticate('authenticator:custom', credentials)
        .then(function(){

          // error: TypeError: Cannot read property 'set' of undefined
          this.set('userSessionStorage.username', credentials.identification);

        })
        .catch((message) => {
          console.log("message: " + message);

          this.controller.set('loginFailed', true);
        });
    }
  }
});




Cannot play offline video in production electron app

I have an electron/ember app that allows users to store a video offline and play it later. The ember app uses a video tag with a computed property to swap out the video src from the server with the offline link. I am storing it using electron.getPath("userData") so for macOS it's in ~/Library/Application Support/<appname>. The problem comes when I create the signed distributable. The offline support works just fine when running with ember electron but as soon as a I sign and package it for release it no longer works. The video player itself loads but is just blank. Is there some limitation with using local files in release mode for electron?




Ember nested route not rendering template

I am using the latests ember-cli version 2.12.1 and ember.

I have configured my routes as this:

 Router.map(function() {
  this.route('companies', function() {
  this.route('companydetail', {
  path: '/:company_id'
    }, function() {
      this.route('employees', function() {
        this.route('employeedetail', {
          path: '/:employee_id'
        });
      });
    });
  });
});

The templates are in

/templates/companies/index.hbs
/templates/companies/companydetail.hbs
/templates/companies/companydetail/employees/employees/employeedetail.hbs

I can link to the route

Edit

and that works. But the template is not rendered. Instead the companydetail.hbs is used. I changed the /routes/companies/companydetail/employees/employeedetail.js to render the correct template:

renderTemplate: function(params) {
    this.render('companies/companydetail/employees/employeedetail', {
      into: 'application'
    });
}

This is working, BUT: the call to the model (request to the server) is not done. I could try and make the call manually, but I start to believe, that I am doing something wrong with the route.

Any advice?

Thanks in advance, Silas




post form data to rest api from Ember component

I'm trying to post data from an input and a button group in a component using Ember to my REST API using the actions up method, but the code is confusing me a bit and I haven't found a clear example of how to do it.

The site is a tracker for competitive games in Overwatch, so enter the rank after the game and see it in a list. There is one table, and one endpoint with no children in the API. Basically a simple to-do app, but i'm using components to keep everything modular. I also want to add edit and delete, but that is out of scope for this question.

app/templates/components/add-game.hbs

<form class="form-inline">
  <div class="form-group">
    <label class="control-label">
      Rank <small>(After match)</small>
      
    </label>
  </div>

  <div class="form-group">
    <label class="control-label">
      Outcome
      
        Win
        Draw
        Loss
      
    </label>
  </div>

  <div class="spacer"></div>

  <div class="form-group">
    <button  type="submit" class="btn btn-default btn-primary">Save</button>
  </div>
</form>

app/components/add-game.js

import Ember from 'ember';

export default Ember.Component.extend({
   actions: {
        saveGame() {
            const outcome = this.get('model.outcome');
            const rank = this.get('model.rank');
            console.log(outcome);
            console.log(rank);
        }
  }

});

app/application.hb


<div class="container-fluid">
  <div class="row">
    <div class="col-md-offset-2 col-sm-8 col-md-8 main">
      
      <br>
      
    </div>
  </div>
</div>



I feel like I have most of it there, im just missing a few things with the Data Down, Actions Up approach that Ember uses, but haven't found a clear example to work off that is similar to my code. As you can probably tell I've got the code sending the data to the console, but im not sure of the best way to send it up to the route to then be sent to the server. I think I need to use the model, but the specific code

I am using ember-bootstrap for the styling and custom button group component.

The whole project is on Github




Using Steamcommunity as an OpenID provider to authenticate with Torii

I was wondering how you can use Torii to authenticate users in an ember-cli application. Torii has a lot of providers for OAuth authentications but there are none for OpenID.

I have tried to create a server-side NodeJS application that handles authentication with Steam using Passport, but I'm not sure how to connect that with my Ember app to verify if the user is authenticated and retrieve details about their profile.

Do I have to create a custom authenticator or provider for Torii in order to sign in with Steam? Thank you.




ember: pushPayload error in instance initializer

I'm trying to preload my cart model on init and am getting the error

TypeError: cart.pushPayload is not a function

I know that not all serializers have this function, but the one I am using (RESTSerializer) does. My serializer for application.js is:

import DS from 'ember-data';
export default DS.RESTSerializer.extend({});

The instance-initializer for cart.js is:

import Ember from 'ember';

export function initialize(appInstance) {
    let CartService = appInstance.factoryFor('service:cart');

    let payload = {
        "cart": [{
            "id": "S5339",
            "quantity": 1,
            "itemPrice": 129.95
        }, {
            "id": "BLK1642",
            "quantity": 1,
            "itemPrice": 55
        }, {
            "id": "TDS9004",
            "quantity": 5,
            "itemPrice": 99.95
        }]
    };
    let cart = CartService.create();
    cart.pushPayload(payload);

    appInstance.register('cart:main', cart, { instantiate: false });
    appInstance.inject('controller', 'cart', 'cart:main');
    appInstance.inject('component', 'cart', 'cart:main');
}

export default {
    name: 'cart',
    initialize
};

For now I am using static data but if/when I get this working I will be doing a network request using ember-network.

But I'm going down the rabbit hole on why I can't get pushPayload to work. Any help appreciated!




vendredi 21 avril 2017

ember: using cookies with ember-network

Can cookies be used with ember-network requests? Thanks to this answer I know that they can be used with ember-data API requests, but I need to do a network request in an initializer and it doesn't appear the ember-data store can be accessed that early.

Background:

I'm wanting to persist shopping cart data to the backend for these reasons

The ember-cart addon has a smart way of persisting the cart by jsonifying and data model and dumping to localstore when it changes:

window.localStorage.setItem('cart', JSON.stringify(this.payload()));

then upon return visit parsing the json and pushing it into the store in an instance initializer:

...
payload = JSON.parse(payload);
...
cart.pushPayload(payload);

I'd like to do basically the same thing, but instead of getting the JSON from localstorage, get it from the API via the network.

the store ins't available in an initializer, but ember-network is. So hypothetically I think I can do this. The problem I'm running into is that the cookie isn't being passed.

I get around this with ember-data by using this:

  xhrFields: {
    withCredentials: true
  }

in the application adapter, but I can't find any info about whether there's a similar setting for ember-network. I see the request to my API being made in the initializer, but the api doesn't return anything because the browser cookie isn't included.




Image not fingerprinting within components - EMBER

Images display in development mode but once deployed into production do not display because they do not seem to be compiled like other assets.

This is only within components, other images within a template display.

Example Component:

podcast-header.hbs:

<div class="banner-block">
    <img src="/images/podcasts_browseshows_header.jpg" class='bw-stretch-image'>
    <div class="title-overlay-bottom">
    <img src="/images/podcasts-button.png">
    </div>
</div>

Thoughts? Is this a bug to be reported or am I missing something?




How to dynamically switch disabled=true/false of an input text inside Ember Component?

I have an Ember component that I want to dynamically disable/ enable. Initially I have:

//template.emblem
= input type="text" disabled=true placeholder="Account Number" class="form-control"

When I have disabled=false, it enables the button again. Now I want to make it dynamic. I thought of creating a simple function that returns true or false inside component.js:

//component.js
export default Ember.Component.extend({
  ...
    disableButton(){
    return true
  },

//template.emblem
  = input type="text" disabled=disableButton placeholder="Account Number" class="form-control"

This disables it. However, when I switch disableButton to return false, it is still disabled.

How can I connect the disabled to a function/ property inside component.js?

The template.emblem and component.js folder hierarchy is:

components
  |-my-awesome-component
    |- template.emblem
    |- component.js




ember-simple-auth, acceptance tests and waiting for async actions

Struggling with acceptance tests. Started with basic login test:

import { test } from 'qunit';
import moduleForAcceptance from 'static/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | authentication');

test('login', function(assert) {
  visit('/');
  click('.nav-bar__login-link');
  andThen(function() {
    assert.notOk(find('.login-form__submit-button').attr('disabled'));
  });

  fillIn('.login-form__email-block input', "ruz@email.com");
  fillIn('.login-form__password-block input', "qwe");
  click('.login-form__submit-button');

  andThen(function() {
    console.log("ftw");
    assert.equal(find('.nav-bar__profile-link').text(), "some");
  });
});

The problem is that andThen callback is called before authentication completes. It's jQuery ajax request and a few promises after. From what I can see ember waits for ajax query to complete, but doesn't wait for promises to get resolved/rejected. Should this test work out of the box? Do I have to write a custom waiter?




Hiding EmberJS Route instead of Destoying

Is there a way to hide templates of EmberJS routes instead of destroy them?

There are a lot of old post about this but still no official way to achieve this.




Computed property in model with belongsTo returns undefined

I have 3 models.

// Product
export default DS.Model.extend({
    content: DS.attr('string'),
    creator: DS.belongsTo('user')
});

// User
export default DS.Model.extend({
    email: DS.attr('string'),
    products: DS.hasMany('product'),
    person: DS.belongsTo('person'),
    fullName: Ember.computed(function() {
        return `${this.get('person.firstname')} ${this.get('person.surname')}`;
    })
});

// Person
export default DS.Model.extend({
    firstname: DS.attr('string'),
    surname: DS.attr('string'),
    users: DS.hasMany('user')
});

I try to use this in handlebars.


    


As you can see there is a computed property in the User model. But it returns always undefined undefined because this.get('person.firstname') and this.get('person.surname') return undefined.

The Ember inspector shows data for each model. Any idea how to fix this?




Enable only next seven day in moment-format component

In ember i am using component of npm package ember-moment

How can i enable only next seven days?




How to save nested objects in ember js

In a related question I wanted to know How to add parent object to child in a one-to-many relationship in ember.js. Now I want to know how to simultaneously save them on the server when creating or updating the parent with a newly created child.

The server would expect something like this:

parent {
    prop1: 'val1',
    prop2: 'val2',
    child: {
        prop1: val1
        prop2: val2
    } 
}

but ember's payload looks like this:

parent {
    prop1: 'val1',
    prop2: 'val2',
    child:null
}

The same goes for updates when having an already existing child appended to the parent. Then the payload looks something like this:

parent {
    prop1: 'val1',
    prop2: 'val2',
    child:2
}

So it's not the child-object transferred with the payload but only it's id if existing (otherwise null)). Is it possible to send a nested object like the server expects or do I have to save both models separately with two ajax-post/put-requests.?




Render table component with 500 rows block browser?

I have a component which render 500+ data into a HTML table rows

It take almost 3 seconds to render and the browser is completed blocked.

I cannot use pagination because the client want it excel-like and it is a static site.

Is there a way to solve this issue? For example create a loading state before the component is rendered?




jeudi 20 avril 2017

Custom query function for Ember Data adapter

I'm trying to override my default query function in my application adapter. I'm using query to get data from the backend, when the application goes offline I'd like to query only the data currently stored in the cache, in the style of .peekAll().

This is what I have so far.

// adapters/application.js
  
// turns to cache when no connection available
export default DS.JSONAPIAdapter.extend({
  // ...
  query(store, type, query) {
    let isOnline = this.get('isOnline'); // updates according to connection, returns true or false
    return isOnline ? store.query(type, query) : store.filter(type, query);
  }
}

but my problem is I'm not able to execute the query function within the query function properly. Not sure what's the problem here, I tried wrapping this in promises or returning with .then().

// can't get this to work
query(store, type, query) {
    return store.query(type, query);
}

I feel like once I get that right, the rest won't be much of a problem.

Any help, ideas or workarounds much appreciated!




Ember JS - Update property on all instances of a component

Is it possible to update a property on all instances of a component?

If I have 10 instances of the component below on a page, I would like to set the currentTrack property to false on all of them. Is this possible? Can it be done from inside one of the components?

import Ember from 'ember';

export default Ember.Component.extend({

    currentTrack: true,

});




Ember fails to create an instance of 'authorizer:token' using ember-simple-auth and ember-simple-auth-token

I'm trying to implement JWT authentication into my Ember application using the ember-simple-auth and ember-simple-auth-token modules by following their README files on GitHub. I got the authentication part to work pretty easily. I can send credentials to the authentication endpoint, and get a token back. But then when I try to implement authorization through the JSONAPIAdapter, I get the following error

Error: Failed to create an instance of 'authorizer:token'. Most likely an improperly defined class or an invalid module export.

I'm using Ember 2.12 and have the following setup:

app/adapters/application.js

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
  host: 'http://localhost:8000',
  authorizer: 'authorizer:token'
});

app/routes/users.js

import Ember from 'ember';

export default Ember.Route.extend({
  session: Ember.inject.service('session'),
  model() {
    return this.store.findAll('user');
  }
});

package.json

"ember-cli-simple-auth": "^0.8.0",
"ember-simple-auth": "^1.2.2",
"ember-simple-auth-token": "^2.1.0",




Ember - Chrome - under source tab, not able to debug js files

in ember project the JS files is generated and is integrated with the application WEB .war files. When i access the application URL like http://localhost:4200/applicationName i can see the js files under Source Tab of Chrome, but i am not able to debug those JS files. Also i am not sure this because of the JS files are genarated with some build number like projectname-1221434545kjk345345kj345.js Ideally i have to see the all the JS files with the project structure.

the problem is if i do any changes in JS i have to build all project and there i can see the reflected changes, but same changes reflected i am not able to see on 4200 ember server, the ember server shows the like Build is Success but no changes reflected on 4200 Server?

I need help how should i get changes reflected without complete project Build?




Ember Js 2 + Liferay DXP portlet

I have built an Ember Js 2 application and trying to integrate it into Liferay so that I can use my Ember app as a portlet in Liferay DXP.

Does anyone have a sample application that was already built for this integration so that I can use it as a reference

Please check here for the thread in Liferay forum.




Change event for textarea in ember

So i have this textarea



as you can see above the keypress event works just fine i.e it is able to trigger the upload action

Now when i replace key-press with change or onchange the upload action dose not get fired. Here is the code



How to call change event action in ember for textarea??




mercredi 19 avril 2017

How to adjust flatten function to account for nested objects with an empty value in EmberJS

I have an Ember array that looks something like this: Array Image

Once flattened, it looks like this: Array Flattened

This is my function:

function flatten(parent) {
  return parent.reduce(function(sum, item) {
    var itemVal = get(item, 'value');
    if (isArray(itemVal)) {
      sum = sum.concat(flatten(itemVal));
    } else {
      sum.push(item);
    }
    return sum;
  }, []);
}

But it doesn't seem to work for this array which is 2 levels deep and has no value: First level

Second level

The root level is CONN_INFO -> CFG_SWITCH --> 412 which has no value. I would like to display the flattened array with something like this nested within Class:

key: "CONN_INFO"
value: "{CFGSwitch: {412: {}}}"




Compile Component in Ember 2

I have a component in Ember2 that receives a parameter . I need to pre compile the component and get the generated html.

I have tried to use ember-cli-htmlbars-inline-precompile but without success. let template = hbs";




Ember Computed Property on hasMany relationship not updating and doubles on save

I have two models, one with hasMany relationship to the other:

Shipment:

import DS from 'ember-data';

export default DS.Model.extend({
  pickup_address: DS.belongsTo('address', { inverse: null }),
  delivery_address: DS.belongsTo('address', { inverse: null }),
  shipment_lines: DS.hasMany('shipment-line', { inverse: null }),
  shipmentPrice: Ember.computed('shipment_lines.@each.package_price', function () {
    let price = 0;
    this.get('shipment_lines').forEach(function(shipment_line) {
      price += Number(shipment_line.get('package_price'));
    });
    return price;
  }),
});

And the shipment line model:

import DS from 'ember-data';

export default DS.Model.extend({
    description: DS.attr('string'),
    package_weight: DS.attr('number'),
    package_length: DS.attr('number'),
    package_width: DS.attr('number'),
    package_height: DS.attr('number'),
    package_price: DS.attr('number'),
});

In the controller, when I add new shipment lines to a shipment, I fetch the price for the package from the API and add it to the shipment line:

addShipmentLine(shipmentLine) {
  // Get price for shipment line
  this.getShipmentLinePrice(shipmentLine);

  // Add shipment line to shipment
  let shipment = this.get('shipment');
  shipment.get('shipment_lines').addObject(shipmentLine);
},

The getShipmentLinePrice function (simplified):

getShipmentLinePrice(shipmentLine) {
    ...
    // Get weight and type
    let weight = shipmentLine.get('package_weight');
    let length = shipmentLine.get('package_length');
    let height = shipmentLine.get('package_height');
    let width  = shipmentLine.get('package_width');

    // Fetch price from API
    this.get('price').getPackagePrice(weight, length, height, width).then(
        (price) => {
            shipmentLine.set('package_price', price['price']);
        }
    );
}

And lastly, when I try to print the shipmentPrice in the template, it does not update. Even though the price is returned from the server and shipment_lines package_price is set.

Also, when I save the shipment with shipment.save(); and the route is redirected to the show-page, the price is doubled until I refresh the page. After a page refresh, everything displays correctly.

So the first question is, how can I get the shipment computed property shipmentPrice to update when adding new shipment line objects? Or is it not possible?

The second question is, why is the price doubled after a save?




Ember JS - Passing data between components

Using Ember JS 2.12.0

I have created a component that runs an action on click and receives some data. I now need to pass this data into another component. How would I go about this? The docs do not seem to cover it.

Here is my component template:

<div class="play-button" > 
  <span class="glyphicon glyphicon-play" aria-hidden="true"></span>
</div>

And the component JS:

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

    actions: {
        playTrack(track){
            console.log(track);
        }
    }

});

How can I pass the track object into another component?




Ember dynamic route with nested route inside it

I am kind of new to ember .. and i am having a little problem

the problem is that i want to generate a route with an id and another

nested route inside it for example "doctors/visit/(the visit id)/order

here is my router file

this.route('doctor', function() {
    this.route('visit', {path:'/visit/:visit_id'});
});

my visit file

import Ember from 'ember';

export default Ember.Route.extend({
  model(params){
    return this.store.findRecord('visit',params.visit_id);
  }
});

how can i reference one level new route to make it like the one i wrote in the example ?




redirect user to some URL on device resume

I am building cordova application using ember.

And on app resume event, I want to redirect user to path '/#/location' where i check user's location and updates latitude longitude.

Code is -

document.addEventListener("resume", onResume, false);

function onResume () {
  setTimeout(function () {
    window.location.href = '/#/location';
  }, 100)
}

But its not redirecting to '/#/location'.

Can somebody suggest something about this? What i am doing wrong or how can i acheive this?




mardi 18 avril 2017

Twitter authentication with Ember.js and Rails

I'm using Torii and ember-simple-auth to manage authentication on my front-side, and Knock and Omniauth-twitter on my server. I had no problem with Facebook, but Twitter using Oauth1.0, I have troubles to figure out the flow.

Here is my Torii config :

# environment.js

ENV['torii'] = {
sessionServiceName: 'sessiontorii',
providers: {
  'facebook-oauth2': {
    apiKey: 'API_KEY',
    redirectUri: 'http://localhost:4200/'
  },
  'twitter': {
    requestTokenUri: 'http://ift.tt/2o1IHmW'
  }
}

My route or controller :

# route.js

twitterLogin() {
  var self = this;
  this.get('sessiontorii').open('twitter').then(function(response) {
    console.log(response);

    self.transitionTo('index');
  }, function() {
    console.log('auth failed');
  });
},

A new window is opening and I can login with my Twitter account. My server does the authentication/registration, but I can't figure out how to close this new window and send the token to my front. Is my flow completely wrong ? Or do I miss something ?




How to add parent object to child in a one-to-may relationship in ember js

I have two models in ember.js with a one-to-may relationship. Now I want to create a new child object and need to assign an associated parent object. I can't figure out how to do this. My models are defined with the following code:

model of parent-object

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    children: DS.hasMany('child')
});

model of child-object

import DS from 'ember-data';

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

In the model()-method of the route create a child object.

var child = this.store.createRecord('child');

and then query for the parent-object.

var parent = this.findRecord('parent', 2);

Then I tried to bind them together but anythig I tried failed. For example:

parent.get('child').addObject(child) // or
parent.get('child').pushObject(child) // or
child.set('parent', parent)

These things result in parent not having anything in child and child not having anything in parent. I also did some attempts with async promise resolving but with no success. It would be great if someone could post an example how to manage this.




Get request for a custom url using the store

I'm trying to send a GET request to a custom url at this.get('/transactions/from/:startDate/to/:endDate'); using this.store.query function in Ember-data. How can that be accomplished?




Docker auto update host file for nginx webserver container

I'm trying to access my Docker container with an other url than localhost. The container is a nginx webserver serving static files of an Ember application. My nginxconfiguration looks like this :

server {
    listen       80;
    server_name  my-app.dev;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

And I would like to access my application through my-app.dev:8080. So my Dockerfile looks like this :

FROM nginx:alpine

COPY ./my-app-nginx.conf /etc/nginx/conf.d/default.conf

COPY ./dist /usr/share/nginx/html

EXPOSE 80

And my docker-compose.yml file like this :

version: "2"

services:
  web:
    restart: always
    image: me/my-app:latest
    build:
      context: .
      dockerfile: Dockerfile

    container_name: my-app

    # Keep the stdin open, so we can attach to our app container's process
    # and do things such as debugging, etc:
    stdin_open: true

    # Enable sending signals (CTRL+C, CTRL+P + CTRL+Q) into the container:
    tty: true

    ports:
      - "8080:80"

Everything almost work excpet that I have to modify my hostfile on my host machine to map 127.0.0.1 my-app.dev otherwise it doesn't work.




Ember one-way input does not update it's value

I have an custom component that serves as an input (in my application it does more things, but I've wanted to keep same structure so I've wrapped native input into component).

Then when user changes value of an input, I am calling closure action to format provided value (in that case I am uppercasing it) and set it to some property (which should be visible for user in input).

Problem happens when I paste some lowercased string (for example abc), and then without deleting nor adding anything I just select everything and paste it again. At second paste the formatting closure action is called, even setter of an property is called (I've tried computed property with custom set), but my component's input stays unformatted.

I've provided minimal Ember Twiddle to play with: http://ift.tt/2o0gkpp




Ember Handlebars Generate Table

I am new to Ember/Handlebars and need to generate a navigation table with the form

<table>
    <tbody>
        <tr class="headerRow"><td>Group 1</td></tr>
        <tr><td>item1</td></tr>
        <tr><td>item2</td></tr>
    </tbody>
    <tbody>
        <tr class="headerRow"><td>Group 2</td></tr>
        <tr><td>item1</td></tr>
        <tr><td>item2</td></tr>
    </tbody>
</table>

This will allow me to have groups that can be dynamically expanded/contracted when the headerRow is clicked on.

Sample JSON data looks like

[{groupName: 'Group 1', item: 'item1'},{groupName: 'Group 1', item: 'item2'},{groupName: 'Group 2', item: 'item1'},{groupName: 'Group 2', item: 'item2'}]

I need to iterate through the data and create the tbody groups if the current groupName is different than the last group name. This is a trivial task in Javascript/jQuery to create the html as a string and add open and close tbody and header rows, but how do I do this in Handlebars. I cannot find a way to store the last group in a variable (so I can compare to the current group) while using the Handlebars formatting.

I have accomplished the task of generating the table via a JS string by using a helper function, but I need to attach component actions to the rows in the table. What is the correct way to do this in Ember? I'm using Ember CLI 2.9.1.




TypeError: 'Table' object is not callable

I am using the Tornado backend and ember.js frontend and when i save the data it says TypeError: 'Table' object is not callable. Please help me. I don't know where the error comes from.




Emberfire read data from database that already exists

I am learning to use emberfire but I am having trouble reading data from a database that already exists. In other words, I have an iOS app that uses a firebase database. Data is constantly being changed by users on the iOS app. I am now trying to make a web app, using emberfire, that will read from the same firebase database as the one that the iOS app uses.

The problem is, when I try to use

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return this.store.findAll('users');
  }

});

nothing is found. I am wondering if this is because the data was not written to the database from the emberfire app and therefore it is not aware of the data that the iOS app has written to the database. Does this make any sense? Shouldn't the emberfire app know to search the database for 'users' if it doesn't have any saved in the local this.store ?




Button on jquery datepicker not setting values in ember

I have added 'Today' button in jquery date picker.When i click on this button it is showing today's value on UI but it is not setting value to ember data.

below is code.

function setupDatepickerButtons(input) {
      Ember.run.later(function() {
        var buttonPane = Ember.$(input)
          .datepicker("widget")
          .find(".ui-datepicker-buttonpane");
        buttonPane.find('.ui-datepicker-current').remove();
        Ember.$('<button>', {
          text: "Today",
          click: function() {
            Ember.$(visibleEl).datepicker('setDate', new Date());
            Ember.$(visibleEl).datepicker('hide');
          }
        }).appendTo(buttonPane);
        buttonPane.find("button").removeClass().addClass('btn btn-default');
      });
    }




EmberJS Build Failed with no such file or directory for jquery.js

I have an Ember + Django project that previously worked last week and I have not made a single change since. But now every time I rebuild the project it gives me the following error:

Build failed.
The Broccoli Plugin: [SourceMapConcat: Concat: Vendor /assets/vendor.js] failed with:
Error: ENOENT: no such file or directory, stat '/Users/IFH/Desktop/planner/planner-frontend/frontend/tmp/source_map_concat-input_base_path-http://ift.tt/2pcYVd7'
    at Error (native)
    at Object.fs.statSync (fs.js:844:18)
    at Concat.keyForFile (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/index.js:87:20)
    at Array.map (native)
    at Concat.CachingWriter._conditionalBuild (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/index.js:109:65)
    at /Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/node_modules/broccoli-plugin/read_compat.js:61:34
    at tryCatch (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:539:12)
    at invokeCallback (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:554:13)
    at publish (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:522:7)
    at flush (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:2414:5)

Previously it would create those files in that 'tmp' directory, but now nothing is even being created. Once again, I did not change any file before this error occurred. Please let me know what I should change in order to fix this issue.




upload a file using ember-uploader

I'm trying to figure out how to use ember-uploader, I have the following component (like the one in the README)

export default EmberUploader.FileField.extend({
  filesDidChange: function(files) {
    const uploader = EmberUploader.Uploader.create({
      url: (ENV.APP.API_HOST || '') + '/api/v1/images/',
    });
    console.log(uploader);

    if (!Ember.isEmpty(files)) {
      var photo = files[0];
      console.log(photo);

      uploader.upload(photo)
        .then(data => {
          // Handle success
          console.log("Success uploading file");
          console.log(data);
        }, error => {
          // Handle failure
          console.log("ERROR uploading file");
          console.log(error);
        });
    }
  }
});

The express API endpoint is listening for a POST request.

var saveImage = (req, res, next) => {
    let body = req.body;
    res.json({
      data: body
    });
};

But the body is empty after the request is done. I really don't know how to implement the API endpoint in order to get the file, I tried to see the req object and it doesn't contains the file.

Debugging it, After select a file using the component I get the following info in the console.

js console

Seems that the API endpoint works because I get the following output:

POST /api/v1/images/ 200 27.284 ms - 11

But I can't get the file.




lundi 17 avril 2017

ember helper waiting for an ajax request

i,ve write an ember component when init method they call ajax request

    init(){
    this._super(...arguments);
    const context = this;
    if ((this.get('localStorage').getItem('idProfileDesa')) !== null && (this.get('localStorage').getItem('idProfileDesa')) !== undefined) {
      if ((this.get('localStorage').getItem('idProfileDesa')) !== 0) {
        this.get('registerProfileDesaService').findByProfileFormId(this.get('localStorage').getItem('idProfileDesa')).then(
          function (response) {
            context.debug(JSON.stringify(response));
            context.set("alamat", response.alamat);
            context.set("kodeWilayah", response.kodeWilayah);
            context.set("noTelp", response.noTelepon);
            context.set("lokasiWilayah", response.lokasiWilayah);
            context.set("email", response.email);
            context.set("website", response.website);
            context.set("jumlahDusun", response.jumlahDusun);
            context.set("jumlahRw", response.jumlahRW);
            context.set("jumlahRt", response.jumlahRT);
            context.set("jumlahKepalaKeluarga", response.jumlahKepalaKeluarga);
            context.set("jumlahRumahTangga", response.jumlahRumahTangga);
            context.set("jumlahPenduduk", response.jumlahPenduduk);
            context.set("lokasiKantor", response.lokasiKantor);
            context.set("pos", response.pos);
          }, function (e) {
            context.debug(e);
            context.get('commonService').showNotification(e);
          });
      }
    }
  }

this is worked, but unfortunately my ember helper doesn't waiting for ajax request and said the 'data' is undefined in console log

    import Ember from 'ember';

export function validateIsEmail(params/*, hash*/) {
  let email = params[0];
  let mustHaveChar = ["@",".com",".co.id",".id",".org"];
  let didHasWord = 0;
  mustHaveChar.forEach(function (word) {
    didHasWord = didHasWord + email.includes(word);
  });

  return (didHasWord > 1);
}

export default Ember.Helper.helper(validateIsEmail);

how to make my ember helper waiting for an ajax request?




How to use ember c3 charts using JSON object

How to draw a chart in emberjs with c3. I have a JSON object from my service and intending to use it as a model.




Ember component leaking state

I'm new to Ember and have a leaking state problem. I have a carousel widget that displays one item at a time and allows the user to click previous/next to see each item.

Here's the simplified carousel's component:

<button >Next</button>


Clicking next changes the selectedItem property so the next item is shown.

What I've realized is that the carousel-item component isn't re-initialized every time I move to a previous/next item. The DOM is reused each time, and the component's properties are shared since it's all one instance, which means I can have leaking state.

The alternative I see is to render all the items initially, so each has its own instance:


  


and to hide all but the selected item using CSS. However, this option kind of feels like a jQuery hack -- seems like Ember would have a better way. And I'm only ever showing one item at a time, so I hate to have so many extra DOM nodes when I don't need them.

What is the recommended way to handle this kind of a UI, where you only need one item shown at a time but don't want to share state between items? I'd imagine I should have one instance of the carousel-item component per item, instead of sharing an instance across all of them. But it doesn't feel right to instantiate every single carousel-item at first either. And I can't imagine the Ember way is to worry too much about the DOM details myself (determining which one is shown/hidden based on a class and some CSS).




Alter property of Emberjs

I'm new to EmberJs and I'm working on a project that I need to add properties in javascript and css in templantes generated by ember-cli, my difficulty is in finding the javascript and css files

When I search the project for the class or id, it shows me only what is in the dist that can not be changed

Can anyone with emberJS experience help me make these changes?






Template with i w[enter image description here][1]anna to work:

  <div class="top-banner">
    
    
  </div>

  

  <section class="container destaque noticia">
    
    <div class="row informacoes-news">
      <div class="col-xs-12 noticia-texto">
        }
      </div>
    </div>
  </section>

    
  <div class="col-md-1 col-xs-12 download-container">
      <a class="teste" href="">Download</a>
  </div>