mardi 31 janvier 2017

Ember Duration Picker Component

Is there any Ember Duration Picker Component available to use as duration picker in which it picks only duration like in jquery duration picker.

enter image description here

Help me regarding this.




Library imported manually but it's dependencies aren't available ember.js

I have a javascript library "c-liberator" that I need to use in my Ember application I have imported it manually as it's not a npm or bower package but its dependencies aren't being included, when I try to use one of its functions I get this error

Uncaught TypeError: md5 is not a function

I tried importing the exact md5 module that "c-liberator" uses and If I use it in a function in application.js it works fine so the md5 module works fine it's just that "c-liberator" is not using it.

The code below runs fine in application.js but throws the uncaught type error in "c-liberator"

var creds = md5('username' + ':' + 'pass');

I have also tried installing the md5 library one at a time with bower and npm and confirmed it was referenced by bower.json and package.json, this didn't change anything.

The minified md5 library is in c-liberator/libmd5.min.js and I have also tried putting into ember-cli-build.js which didn't work either

app.import('vendor/c-liberator/c-liberator.js', {
    amdModule: 'clib'
  });
  app.import('vendor/c-liberator/lib/md5.min.js', {
    amdModule: 'md5'
  });

Any help would be really appericated.

Thanks Hamish




EmberJS 2.0 How to avoid Dynamic Segments On route to be always undefined?

I want to access to the dynamic segment on a route but the params are always undefined.

I have the next route defined on the router:

this.route('send', {path: '/send/:solName/:id/:userId'}, function() {});

And In my route I have this:

    export default Ember.Route.extend({
        model: function (params){

        console.info(params);

        return {
             solName: params.solName,
             id: params.id,
             userId: params.userId
         }

        }
      });

Any idea why the params are always undefined?




3-state toggle switch in an ember-light-table

I’m new working with Ember.js and ember-light-table. What I’m looking to do is have a three state toggle switch in one of the columns of my table. Here is a fiddle of the type of toggle switch I’m talking about. At this point I can render the toggle switch in the correct column, however only the first toggle box works. What’s the best ‘ember approach’ to solving this type of issue? I assume you build a component so I did, look at the component and the controller for the table which calls the component in the correct column. What's the best approach to get data out of these toggle switches and into a controller so I can update my database?

Controller

//app/controller/table.js
import Ember from 'ember';
import Table from 'ember-light-table';

const computed = Ember.computed;

export default Ember.Controller.extend({

  toggleIds: [],
  model: [],
  table: null,

  actions: {
    updateModel: function() {
      const store = this.get('store');

      const users = store.peekAll('user');
      console.log("user store: ", users);
    },

    onColumnClick(column) {
      console.log('onColumnClick', column );
    }
  },

  columns: computed(function() {
    return [{
      label: 'Home Team',
      valuePath: 'HomeTeam',
      align: 'center'
    }, {
      label: 'Away Team',
      valuePath: 'AwayTeam',
      align: 'center'
    }, {
      label: 'Score',
      valuePath: 'score',
      align: 'center'
    }, {
      label: 'Winner,
      valuePath: 'winner',
      align: 'center'
    }, {
      label: 'Select',
      align: 'center',
      sortable: false,
      cellComponent: 'toggle-switch' // <-- compnent called here!
    }];
  }),

  setupTable() {
    console.log("got here: ", this.get('model') );
    this.set('table', new Table(this.get('columns'), this.get('model')));
  }

});

Component

// app/templates/components/toggle-switch.hbs

<div class="switch-toggle switch-3 switch-candy">

    
    <label onclick="">ON</label>

    
    <label onclick="">N/A</label>

    
    <label onclick="">OFF</label>

    <a></a>
</div>




this.store.query fails with "The response to store.query is expected to be an array but it was a single record"

I am trying build a small search application with Ember.JS - when I try to do REST call and try to display in the UI it fails with error message as "The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array"

Here is my code Snippet:

  1. application/adapter.js

      import DS from 'ember-data';
      export default DS.RESTAdapter.extend({
      host: 'http://c6403:2222',
      namespace: 'server'
     });
    
    
  2. searializers/results.js

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

tried

    import DS from 'ember-data';

    export default DS.RESTSerializer.extend({
    normalizePayload: function(payload) {
      return {
        title: payload.title,
        description: payload.description,
        type: payload.type,
        url: payload.url,
       };
      }
     });

  1. My router/index.js

      import Ember from 'ember';
      export default Ember.Route.extend({
       model: function (){
    
           var searchtext = "Ambariserver-default-port";
           return this.store.query('results',{ searchtext }         ).then(function(results) {
       alert(results);
      return results;
      });
            } }
    
    
  2. model/results.js

      import DS from 'ember-data';
       export default  DS.Model.extend({
        title: DS.attr('string'),
         description: DS.attr('string'),
         url: DS.attr('string'),
         type: DS.attr('string'),
         searchText: DS.attr('string')
       });
    
    
  3. My JSON response:

       {
     "results": [
        {
         "url": "http://ift.tt/IDrjcF",
         "title": "This is SF KB",
         "description": "This is SF HCC",
         "type": "SF"
           },
        {
        "url": "http://ift.tt/QIus9W",
        "title": "This is SF JIRA",
        "description": "This is SF HCC",
        "type": "JIRA"
        }
     ]
    }
    
    

I am struck here for more than 3 days and need help to resolve this issue. Can you please advise what is wrong with my code. does Adapter and serializer looks fine?




Why does this Ember 2 store.createRecord('foo', {user: .., account: ..}) result in null user?

In this toy Ember 2 app, a user models/user.js and an account models/account.js have identical contents:

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

The final foo models/foo.js belongs-to a user and to an account:

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

The router.js exposes creation of foo belonging to an account and a user:

this.route('accounts', function () {
  this.route('one', {path: '/:account_id'}, function () {
    this.route('foos', function () {
      this.route('new');
    });
  });
});

The account id will come from the route, however the user id will come from somewhere else.

So, a route accounts/one.js exposes the account model:

model(params) {
  return this.store.findRecord('account', params.account_id);
},

A route accounts/one/foos/new.js exposes the create-a-new foo model. It will attempt to find the corresponding user record for the id it knows:

model() {
  let userId = 2; // it comes from "somewhere else"
  return this.store.createRecord('idea', {
    user: this.store.findRecord('user', userId),
    account: this.modelFor('accounts.one')
  });
},

Why does the final resulting model have the correct account but null user?




Ember Mirage: faker output reuse in record creation

I wish to mock a rather poor API that has fields which repeat the data, so I'm trying to create a Mirage Factory to generate some random data

e.g

import { Factory, faker } from 'ember-cli-mirage';

export default Factory.extend({
  "firstName": function () {
    return faker.name.firstName();
  },
  "lastName": function () {
    return faker.name.lastName();
  },
  "fullName": function () {
    // how do I put firstName + lastName here?
  }
});




Ember.js. Filtered model

I have a model with tasks, and i wantto get data filtered by status and show result in different lists.

so i have a construction with does't work as i want.

    tasks: Ember.computed(function(){
        var modelTasks = this.get('store').findAll('task');

        return {
            todo: modelTasks.filterBy('status', 'todo'),
            inProgress: modelTasks.filterBy('status', 'inprogress'),
            done: modelTasks.filterBy('status', 'done')
        };
    }),

I'm new, so please, please be tolerant.




Using an Ember Object inside of an addEventListener function

We are using the pikaday Ember calendar and have it set to be inputless and trigger on the click of a link which calls our ShowDates() function.

<a  .... >

calendar stuff

</a>

What this does is create an ember object within the ShowDates action contained in this and toggles the datePicker property which looks like:

let ShowDates = this.get('datePicker');
this.set('datePicker', !ShowDates);

What we are struggling to do is use this ember object in an event listener that make the object's datePicker property false onclick anywhere on the page which would allow us to close it by clicking anywhere else on the page. Any direction would be appreciated.




Pushing object to store causes model to reload with previously removed objects

I have a feed object that hasMany feed tracks. The template loops through those feed tracks and displays their associated track.


  


When a user decides to like a track, that feed track is removed from the array and another is added from the server response:

shareFeedTrack(feedTrack) {
  this.modelFor('master.feed').get('feedTracks').removeObject(feedTrack);
  feedTrack.share().then((response) => {
    if (response != null) {
      var normalizedResponse = this.store.normalize('feed-track', response);
      this.store.push(normalizedResponse);
    }
  }.bind(this));
}

But when the push occurs, the template displays the previously removed track at the top again, as if the model reloaded and didn't register that the top item had been removed.

I've tried to delete the record and save, but again, after pushing the new object, the feed still shows an empty template for the record that had been removed, as if the object still existed in the relations array.




How to add a parameter to a submit action in Ember?

I have a form with an action defined on submit. I would like to have two buttons that submit the form with a parameter. Here is an example:

<form >
    <input type="text">
    ....
    ....
    <button type="submit">Do Stuff</button>
    <button type="submit">Do Stuff and Other Stuff</button>
</form>

doStuff(doOtherStuff=false){
    //do stuff
    if(doOtherStuff){
        //do other stuff
    }
}

I know I can define two actions on the buttons like this :

<button type="submit" >Do Stuff</button>
<button type="submit" >Do Stuff and Other Stuff</button>

But I would like to befit from the form submission (HTML validation, etc)

Is this something possible, or am I missing something big ?

Thanks!




lundi 30 janvier 2017

How to set internationalization in ember JS with a URL parameter or a variable in route/template

I have a readymade ember app on which i am working. It already has a i18n.js file in the initializer folder and has few lines of code as below

import Ember from 'ember';
export function initialize(/* container, application */) {
Ember.I18n.translations = TRANSLATIONS.en;
}

 var TRANSLATIONS = {
  en: {
      hello: 'Hello'
  },
  fr: {
      hello : 'bonjour' 
  }
 };

 export default {
    name: 'i18n',
    initialize: initialize,
    before: '',
    after: ''
 };

My app has 3 landing pages(french/english/spanish), so when the url for english landing page is clicked i should pass the 'en' parameter to the i18n.js.

I am new to ember and UI development, i went through the guides but was not able to find a specific example for my case




Is Angular.js or Ember.js the better choice for JavaScript frameworks?

I have been researching Angular.js and Ember.js for a new rails project. Angular.js has very good documentation and unit-testing tools. But I could not find any good Ember.js tutorials or documentation. Can anyone please elaborate the pros and cons of each.




EmberJs pagination, how to return to first page?

I am implementing a similar solution to How is ajax pagination handled in EmberJS? for my pagination.

How would I redirect to the initial page when someone enters a page with no data? I.e. I have 3 pages of data and someone enters ?page=4.

I've tried to alter the queryParams:

if (model.get('length') === 0) {
  this.transitionTo({queryParams: {page:'0'}});
}

This works fine, but returns the following error:

TypeError: Cannot read property 'name' of undefined
    at Class.finalizeQueryParamChange (ember.debug.js:27880)
    at Router.triggerEvent (ember.debug.js:30355)
    at Object.trigger (ember.debug.js:50524)
    at finalizeQueryParamChange (ember.debug.js:49635)
    at Router.queryParamsTransition (ember.debug.js:49008)
    at Router.getTransitionByIntent (ember.debug.js:48919)
    at Router.transitionByIntent (ember.debug.js:49026)
    at doTransition (ember.debug.js:49603)
    at Router.transitionTo (ember.debug.js:49096)
    at Class._doTransition (ember.debug.js:29999)

And also tried to alter the controller page variable:

this.controllerFor('my-controller').set('page', 0);

But the later has no effect.




Pushing new object to store causes bug in has many relationship - Ember

So what's going on: I have a feed object that hasMany feed tracks. The template loops through those feed tracks and displays their associated track.


  


When a user decides to like a track, that feed track is removed from the array and another is added from the server response:

shareFeedTrack(feedTrack) {
  this.modelFor('master.feed').get('feedTracks').removeObject(feedTrack);
  feedTrack.share().then((response) => {
    if (response != null) {
      var normalizedResponse = this.store.normalize('feed-track', response);
      this.store.push(normalizedResponse);
    }
  }.bind(this));
}

But when the push occurs, the template displays the previously removed track at the top again, as if the model reloaded and didn't register that the top item had been removed.

I've tried to delete the record and save, but again, after pushing the new object, the feed still shows an empty template for the record that had been removed, as if the object still existed in the relations array.

Nothing is coming from the server that could cause this, so it must be a caching issue. It's driving me crazy. Ember data is great but it seems to make things that should be simple (removing an object and adding another) a stressful endeavor.




Emberjs 2.11.0 strange RSVP behaviour

I've looked at release notes but can't find anything that mentions changes to how RSVPs work, but is there a reason this isn't working?

On the route, a very simple model:

  model() {
    return RSVP.hash({
      posts: get(this, 'store').findAll('post')
    });
  }

and in the template:


  


Returns nothing, however if I use a standard model call such as

  model() {
    return get(this, 'store').findAll('post');
  }

with


  


It works as expected. I've done many many apps on previous 2.9.0 and never had a problem with this...

Little confused!




Fine-tune refreshing of multiple models in Ember route

There's a well known approach to support loading more than one model promise in an Ember route, using Ember.RSVP.hash:

// app/routes/posts.js

export default Ember.Route.extend({

  model(params) {
    return Ember.RSVP.hash({
      posts: this.store.findAll('post', params),
      tags: this.store.findAll('tag', params),
    });
  },

});

Now I have a page param, to be able to load the posts in batches, instead of loading them and showing them all at once. But page changes do not alter the tags. However, when the page param changes, the whole model of the route is triggered again to re-load, causing the app to re-fetch both the posts for the new page, and the same tags all over again.

Is there a way to fine-tune this so that the tags are not loaded when certain params change?




EmberJs - Is there a way to tell ember to insert the main-view after the rootElement?

Hi I would like to know if the is a way to tell ember to initialize immediately after the root Element?

For example I have this DOM Structure:

<div id="#bodyContent" class="ember-application">
   <div data-name="ContentPlaceHolderMain">
   </div>
   <div id="ember357" class="ember-view">
   </div>
</div>

But I Want ember to be first on the DOM:

<div id="#bodyContent" class="ember-application">
   <div id="ember357" class="ember-view">
   </div>
   <div data-name="ContentPlaceHolderMain">
   </div>
</div>

In my enviroment.js file I have this line:

ENV.APP.rootElement = "#bodyContent";

Is there any way to achieve this?




Pagination in Ember using ember-cli-pagination

I'm trying to implement pagination on my project using ember-cli-pagination but it's not working. I have something like this in the controller:

import Ember from 'ember';
import pagedArray from 'ember-cli-pagination/computed/paged-array';

export default Ember.Controller.extend({
  // setup our query params 
  queryParams: ["page", "perPage"],

  // set default values, can cause problems if left out 
  // if value matches default, it won't display in the URL 
  page: 1,
  perPage: 10,

  // can be called anything, I've called it pagedContent 
  // remember to iterate over pagedContent in your template 
  pagedContent: pagedArray('car', {pageBinding: "page", perPageBinding: "perPage"}),

  // binding the property on the paged array 
  // to a property on the controller 
  totalPagesBinding: "pagedContent.totalPages"
});

In the documentation, where I've put car is named content. I imagine it's an array of the objects I want to paginate.

The project is here http://ift.tt/2jw2Jz9 at emberdata branch.

I would appreciate if anyone could help me out.




Ember inject function

I have some function which i use in couple controllers

 App.AController=Ember.Controller.Extend({
    area:function(){}
});
App.BController=Ember.Controller.Extend({
    area:function(){}
});

cause i new in Ember i want something to write function in one place and then inject function in Controllers. I try something with services but doesn't work i got error that Ember.Service is not defined, so if someone can write example! I use ember 1.10.




Ember.Route - Model hook is called twice instead of one

I would like to redirect an incomplete URL to a complete correct URL:

http://localhost/product/12/a-single-pr -> http://localhost/product/12/a-single-product-name

The problem is that the model hook is called twice instead of one, making two identical requests to retrieve a single object. Any clues?

routes/product.js

import Ember from 'ember';

export default Ember.Route.extend({
  afterModel(model, transition) {
    let formatted = model.get('formatted');

    if (transition.params.product.formatted !== formatted) {
      let path = '/product/' + model.id + '/' + formatted;
      this.replaceWith(path, model);
    }
  },
  model(params) {
    return this.get('store').findRecord('product', params.product_id);
  }
});

router.js

...

Router.map(function() {
  this.route('product', {path: '/product/:product_id/*formatted'});
});

...




Ember.js: param value is not set in nested route

I'm currently trying to refactor a project from legacy ember (made by Rob Connery in pluralsight) to a ember-cli project. I get the following error: This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid. I think it is the param "repoName" is not passed or set I have the following routes:

Router.map(function() {
  this.route("user", { path: "/users/:login" }, function() {
    this.route('repositories');
    this.route('repository', { path: "repositories/:repoName" } ); 
  });

The parent route "user":

return Ember.$.getJSON("http://ift.tt/1gcW4Wp" + params.login);

the two nested routes "user.repositories" and "user.repositry":

model: function (params) {
    return Ember.$.getJSON(this.modelFor('user').repos_url);
  }

model: function (params) {
    var user = this.modelFor("user");
    var url = "http://ift.tt/19e4Tso" + user.login + "/" + params.reponame;
    return Ember.$.getJSON(url);
  }

So when i try to link to a specific repository in my template:

<h4></h4>

Then nothing happens. I want to call the repository route with the current user.

I'm quite new to ember so please forgive me if the conventions is not accurate.

The whole project is about getting the git repositories from your choice of developers, see their repositories and eventually the commits, forks and issues. If you want to see the whole project and/or contribute you can find it here:

http://ift.tt/2jmDN1L




Buttons: Change value by ID in Ember.js

I‘m trying to have a set of buttons in an <button>...</button> block, and to get the target values by an ID of the model ...

Let’s say there is a controller with model and action:

export default Ember.Component.extend({

    Texts: [
        {id: "1", name: "One", sample: "Hello!"},
        {id: "2", name: "Two", sample: "Hello! Hello!"},
        {id: "3", name: "Three", sample: "Hello! Hello! Hello! "},
    ],

    theText: "Test",

    actions: {
        setText: function(id) {
            var theText= this.get('Texts.sample', id);
            this.set('theText');
            console.log(theText);
        }

});

and this in the template:


    <button ></button>


<span></span>

... this is my idea, but all I get is an undefined ...




Ember observer not working on nested property

I have created a mock application to illustrate the situation I am facing: Mock App

In this application; I have created a service with a single boolean property and a function to toggle that property (x); and two components (one to toggle the service's property; the other to observe the number of toggles and display it). The observer lies in toggle-observer. It is added directly to service's property as: myService.x. The code is not working as is; however if the comment at line 14 of toggle-observer.js is commented out; the observer starts working.

My question is that, do I need to perform a get to the whole path of a nested observer property to get it working? Is this the expected behavior? If so, can somebody explain why? My best regards.

Note: This is a mock example to illustrate the case; it is not related to anything I am designing in a real app. I am trying to avoid observers as much as possible; but I ran into this situation while trying out sth. and decided to ask it.




Unit testing service in EmberJS: How to prevent interaction between tests?

I'm seeing a strange interaction when writing unit tests for services in ember.js. It only occurs on arrays.

I'm having a service which has an array as property. The state of array is shared between different tests. I don't see this behavior if property has a simple type (e.g. number). Do you have any hint what's going on?

Here is a ember-twiddle demonstrating the issue: http://ift.tt/2jJQe64




Access-Control-Allow-Origin error in ember.js

I'm using ember.js and it is throwing me this error:

XMLHttpRequest cannot load http://ift.tt/2kFIFMf. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

On my server side, I have placed codes to print out a log for GET, POST and PUT calls. It does NOT print out anything. Therefore, I think the client-side never made any requests to the server. (However, access 'http://ift.tt/2kFIFMf' manually does indeed invoked the log on the GET method.)

The server-side is already coded to return the Access-Control-Allow-Origin and it works for other methods.

So, what is my problem?

And just for for the record, the server side in Java is:

responseBuilder.header("Access-Control-Allow-Origin", "http://localhost:4200");
responseBuilder.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, auth-token");
responseBuilder.header("Access-Control-Allow-Credentials", "true");
responseBuilder.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
responseBuilder.allow("OPTIONS");

and in my ember.js config/environment.js I have:

ENV['contentSecurityPolicy'] = {
        'default-src': "*"
    };




Order of ember-cli preprocessors

I'm the maintainer of the ember-cli preprocessor for java.properties files to generate a JS file exporting a JSON object with values. The problem I'm running into is that the file is correctly processed (ES2015 flavored), but that files is not transpiled into ES5.

The generated app.js file contains this statement: export default {"foo":"bar"} but that should be transpiled into something like this:

define('my-app/locales/en', ['exports'], function (exports) {
  exports['default'] = {"foo":"bar"};
});

Is it possible to generate the ES2015 flavored file and after that run the default transpiler to create the ES5 variant?




"UnrecognizedURLError" ember startup probs

Using http://localhost:4200/index.html as the base URL, need to route to dashboard on load of my application ..added route for dashboard in router.js




Ember Data not sending to server

I have the following code:

app/models/account.js:

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  birthdate: DS.attr('date'),
  gender: DS.attr('boolean'),
  emailaddresses: DS.attr()
});

and app/components/account-profile.js:

import Ember from 'ember';

export default Ember.Component.extend({
  buttonLabel: 'Send to Server',
  actions: {
    buttonClicked(param) {
      this.sendAction('action', param);
    }
  }
});

and app/templates/components/account-profile.hbs

<div class="box">
  <div class="title">Your Profile</div>
  <div>Username: </div>
  <div>Email Address: </div>
  <div>Birthdate: </div>
  <div>Gender: </div>
</div>
<div>
  <div>
    <label>Username</label>
    <div>
      
    </div>
    <label>Username</label>
    <div>
      
    </div>
    <label>Username</label>
    <div>
      
    </div>
    <label>Username</label>
    <div>
      
    </div>
    <div>
      <div>
        <button type="submit" ></button>
      </div>
    </div>
  </div>
</div>

I do not see any traffic being sent from from my web browser to my server.

What is missing and what's wrong with my code? What other things I need to do?




dimanche 29 janvier 2017

How to load nested records (master-detail records) using Ember Data?

The master record, app/models/account:

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  emailaddress: DS.hasMany('emailaddresses'),
  birthdate: DS.attr('date'),
  gender: DS.attr('boolean')
});

The detail record, app/models/emailaddress:

import DS from 'ember-data';

export default DS.Model.extend({
  account: DS.belongsTo('account'),
  emailaddress: DS.attr('string'),
  verificationcode: DS.attr('string'),
  isverified: DS.attr('string')
});

The dummy JSON string from the server:

{"id":0,"username":"ikevin","birthdate":"Jan 30, 2017 1:34:38 PM","gender":true,"emailaddresses":[{"id":0,"emailaddress":"aaa@bbb.com","verificationcode":"AAAAAA","isverified":false}]}

The adapter /app/adapters/account.js

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({

  urlForQueryRecord(query) {
    if (query.profile) {
      delete query.profile;
      return `${this._super(...arguments)}/profile`;
    }

    return this._super(...arguments);
  }

});

The route app/route/index.js:

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend({
  model() {
    return RSVP.hash({
      walletbalance: this.get('store').queryRecord('wallet', {balance: true}),
      instagramfriendscount: this.get('store').queryRecord('instagram', {friendscount: true}),
      accountprofile: this.get('store').queryRecord('account', {profile: true})
    });
  }
});

And the app/templates/components/account-profile.hbs:

<div class="box">
  <div class="title">Your Profile</div>
  <div>Username: </div>
  <div>Email Address: </div>
  <div>Birthdate: </div>
  <div>Gender: </div>
</div>

I think there are 2 problems here:

  1. In the Chrome Ember plugin, the data for model type "emailaddress" is always 0. So, that means it is not loaded.

  2. In the app/templates/components/account-profile.hbs, is not referring to the correct field. Note: for now it is expected to display only 1 email address.

How do I resolve these problems to load and display nested records?

Thanks!




How to send data to server using ember.js Ember Data?

I'm trying to save (persist) data from the web application client using ember.js / Ember Data to the server which is accepting standard API calls. I have tried the code on the documentation but it just does not work. I also cannot find any example application as a guide.

The model is:

/app/models/account.js:

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr(),
  emailaddess: DS.attr(),
  birthdate: DS.attr(),
  gender: DS.attr()
});

/app/adapters/account.js:

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({

  urlForQueryRecord(query) {
    if (query.profile) {
      delete query.profile;
      return `${this._super(...arguments)}/profile`;
    }

    return this._super(...arguments);
  }

});

I'm asking for help for the code (including the adapter, model and template (.hbs) HTML button) working together to send data (using Ember Data) to the server. Thanks!




Ember.js - Controller not picking model data

I have a model which has this field

diaryItemLabel: DS.attr('string'),

I want to access the data from this field in my controller.

Controller.js

enter image description here

I want to replace the 'Add' with whatever data I get from diaryItemLabel.

I cannot use this.get('model.diaryItemLabel'). It gives me this.get() is not a function. I tried using Ember.get('model', 'diaryItemLabel'). It gives me empty string.

Could someone guide me to the right direction?

Thanks




You need to pass a model name to the store's modelFor method

I have problem with making hasMany <=> belongTo relationship to work.

I have articles/show view, when I try to list article's comments but I keep recieving the error pointed in the title.

It's something with belongsTo: DS.belongsTo('article') but I couldn't figure out what it is.

Here are my files.

routes/articles/show.js

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend({
  model(params) {
    return RSVP.hash({
      article: this.store.find("article", params.id),
      comments: this.store.query('comment', { articleId: params.id })
    });
  }
});

controllers/articles/show.js

import Ember from 'ember';

const { computed: { alias, readOnly } } = Ember;

export default Ember.Controller.extend({
  article: alias('model.article'),
  comments: alias('model.comments'),
  length: readOnly('comments.length')
});

templates/articles/show.hbs

<h3>Comments ()</h3>

  <p>Author: </p>
  <p>Somebody said: </p>


adapters/comment.js

import ApplicationAdapter from './application';
export default ApplicationAdapter.extend({});

serializers/comment.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  attrs: {
    user: { embedded: 'always' },
    article: { embedded: 'always' }
  }
});

serializers/article.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    comments: { embedded: 'always' }
  }
});

models/article.js

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

const { attr, hasMany } = DS;
const { computed: { gt } } = Ember;

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

  authorName:   attr('string'),
  authorAvatar: attr('string'),
  authorUrl:    attr('string'),

  comments:     hasMany('comment', {async: true}),

  hasAvatar: gt('authorAvatar.length', 0)
});




how to update model from the Route function

I am trying to write small search application but am struck at updating the model based on some action.


import Ember from 'ember';

model/index.js: import DS from 'ember-data';

 export default  DS.Model.extend({
 searchText: DS.attr('string'),
 title: DS.attr('string'),
 description: DS.attr('string'),
 url: DS.attr('string'),
 source: DS.attr('string')
});

route/index.js: export default Ember.Route.extend({

  actions:{

    submitsearch: function(inputsearchtext) {
    var data = {
      "searchText": inputsearchtext
    }

     var models = this.model.values;
     alert(models);
    Ember.$.ajax('http://c6403:2222/server/getkb', {
      type: 'POST',
      dataType: 'json',
      contentType: "application/json",
      data: JSON.stringify(data),
      async: false,
      context: this,
  }).then(function(response) {
      var type = response.type;
      var payload = response.payload;
      alert(payload);
      this.store.pushPayload(type, payload);
   });

   }

 }
});


Basically I wanted to update my model based on the searchtext user has provided. As part of this I am making "submitsearch" call and from there trying to make a AJAX/json call - once I get the json response I will have to update model so that my view will be updated/refreshed.

here is my questions:

  1. json response "payload" is undefined though server returns proper response - I could validate the response in browser.

  2. after getting the payload what is the correct way to update the model so that component should be refreshed to show the results.




How to pass selected value between routes

I am quite new to the EmberJS, so please help me to understand and solve my problem.

This is my model: book.js

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    author: DS.attr('string'),
    picture: DS.attr('string'),
    buyer: DS.attr('string'),
    bought: DS.attr('boolean', { defaultValue: false }),
    createdAt: DS.attr('date', { defaultValue() { return new Date(); } })
});

I have the following route: Books.js

import Ember from 'ember';

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

and a bit from corresponding books.hbs


        <div class="book-container col-xs-12 col-sm-6 col-md-4">
            <div class="card">
                <div class="wrapper">
                    <div class="details col-md-12">
                        <h3 class="product-title">Title </h3>
                        <p class="product-description">Author:</p>
                         Buy 
                    </div>
                </div>
            </div>
        </div>


This code returns all the books that I currently store in the app.

The idea is to get selected Book object from books.hbs and display it in give.hbs.

I wanted to use this line

Buy

to pass single a single book from books.hbs to give.hbs, but I don't know how to do that and if its the way to go..

In gift.hbs I partially invented a very inefficient way of doing it by looping all the books again and if the title is a match then display it...

  
    
      <h2><b></b></h2>
    
  

Obviously the "Harry Potter" string is hard coded but it could have been passed from books.hbs and that would do the trick since my data is relatively small.

If any Ember.js Guru could show me the proper way of doing that, that would be much appreciated.

Thanks




Can't find variable: Promise on iOS 7

iOS 7 Safari is reporting the error Can't find variable: Promise:

new Promise(function(resolve, reject) {
.
.
.

White other browsers don't have this issue, I found this similar question where Robert gave a solution to add new Ember.RSVP.Promise instead of the new Promise.

My problem is that I'm not using jQuery and that makes all browsers return an error that Ember is not defined, and I found that adding Ember.min.js solves the issue, but that adds extra 129.96 KB to my page which is not good at all to my project.

I just want to fix the problem for iOS7, and I appreciate if somebody who knows how he tell us.




How to customize(? or add path to) ember.js Ember Data RESTful URI?

Say, I have the following code:

In app/adapters/instagram.js:

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({

  urlForQueryRecord(query) {
    if (query.friendscount) {
      delete query.friendscount;
      return `${this._super(...arguments)}/friendscount`;
    }

    return this._super(...arguments);
  }

}

It will go out to http://localhost:20000/instagrams/friendscount to retrieve the data.

How do I make ember.js go out to "http://localhost:20000/socialnetworks/instagrams/friendscount"? (add "socialnetworks" into URI. Note that this "socialnetworks" is before the "instagrams".)




Need help to understand how ember.js Ember Data works

I am very new to ember.js.

I have the following code which I need to change to retrieve data from the server using multiple models (using multiple JSON/RESTful calls).

This (single model version) WORKS:

In app/routes/index.js:

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.get('store').queryRecord('wallet', {balance: true});
  }
});

and in wallet-balance.hbs:

<div>Your Total Score:  </div>

I changed to this and it WORKS:

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend({
  model() {
    return RSVP.hash({
      wallet: this.get('store').queryRecord('wallet', {balance: true})
    });
  }
});

and in wallet-balance.hbs:

<div>Your Total Score:  </div>

BUT if I change to the following ("wallet" -> "anythingelse"), it WON'T WORK:

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend({
  model() {
    return RSVP.hash({
      anythingelse: this.get('store').queryRecord('wallet', {balance: true})
    });
  }
});

and in wallet-balance.hbs:

<div>Your Total Score:  </div>

I'm trying to understand why. Where is it picking up from for the definintion "wallet" - and why changing to "anythingelse" won't work? Where else is the code for "wallet" referring to?




samedi 28 janvier 2017

jQuery dropdown issue (submenu doesn't stay visible)

I'm using Jquery to display a dropdown menu when the mouse hover over navigation links, it's working although the submenu doesn't stay visible when the mouse hover over it, I think the issue is that I'm not nesting my submenu inside the navigation. And that's on purpose. Here's my jquery code with hoverIntent implemented (used to control sensitivity of hover):

The missing part is keeping the submenu visibile until the user clicks anywhere on the body tag or on another navigation link, but not on the submenu of the current navigation link.

A codepen is well commented and available: http://ift.tt/2kGvVnO

jQuery(document).ready(function($) {
var config = {   
     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)   
     interval: 100,  // number = milliseconds for onMouseOver polling interval   
     over: doOpen,   // function = onMouseOver callback (REQUIRED)   
     timeout: 0,   // number = milliseconds delay before onMouseOut   
     out: doClose    // function = onMouseOut callback (REQUIRED)   
};

function doOpen() {
    $(this).removeClass('PopupClosed').addClass('PopupOpen');
    var cls = $(this).data('target'); // fetch which class to target.
    $('.Menu.' + cls).css('display','block'); // will make display block
}

function doClose() {
    $(this).addClass('PopupClosed').removeClass('PopupOpen');
    var cls = $(this).data('target'); // fetch which class to target.
    $('.Menu.' + cls).css('display','none'); // will make display none
}

$(".navTab.Popup").hoverIntent(config);
});




Ember assets broken in nested route template

I created a nested route under an existing route.

Router.map(function(){
 this.route('parentRoute', function(){
    this.route('childRoute');
  });
});

Prior to the nesting, I had the newly nested route as a sibling to the now parent route. At the time, I was able to load assets using the normal method

<img src="assets/images/profile/pic.svg" alt="" />

But after creating the nested route, putting the above in the nested route's template is giving me a 400 file not found error.

Any suggestions?




nginx 405 - uploading img from ember to rails

I implemented an image upload in Ember, with dropzone addon. Rails 5 is running on the server (Ubuntu 14.x), imagemagick is installed in the Rails Docker Container and all files should go to the folder "uploads". Everything is running as docker containers, so rails, frontend, database and nginx (1.11.4) are seperate containers. Now, if I try to upload an image, the server response is a 405 and rails didn't get anything (nothing in the log).

rails uploader.rb

class AvatarUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :thumb do
    process resize_to_fill: [200, 200]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_whitelist
    %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  def filename
    return unless original_filename
    contenttype = original_filename.split('.').last
    "avatar.#{contenttype}"
  end
end

nginx config

server {
  listen 443 ssl;

  server_name example.com;

    ....
    ssl stuff
    .... 

  location / {
    proxy_read_timeout 150;
    proxy_set_header        Host $host:$server_port;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;
    proxy_pass http://backend:3000;
  }

}

Request: Request img details

Response: Response img output

If i put the following line into the neginx config (like recommended 100 times on stackoverflow)...

error_page  405     =200 $uri;

... the server throws the error:

Can not read property 'attributes' of undefined

This error message is from dropzone. It can't complete the upload. In rails there is nothing received, no entry in logs, nothing...




Allowing Access-Control-Allow-Origin from anywhere (Java and ember.js)

I am using Java Jersey and Jetty on my server-side and have the following piece of code:

    responseBuilder.header("Access-Control-Allow-Origin", "http://localhost:4200");
    responseBuilder.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, auth-token");
    responseBuilder.header("Access-Control-Allow-Credentials", "true");
    responseBuilder.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    responseBuilder.allow("OPTIONS");

and I'm using ember.js on my client-side and have the following code:

/app/adapters/application.js:

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host: 'http://127.0.0.1:20000',

    ajax(url, method, hash) {
        hash = hash || {};
        hash.crossDomain = true;
        hash.xhrFields = {
            withCredentials: true
        };
        return this._super(url, method, hash);
    }
});

The combination of the code works that it sends the COOKIE as part of the request and resolves the Access-Control-Allow-Origin problem.

However, my concern is that the "http://localhost:4200" is hard-coded. While it is not a problem until deployment, I suppose this restricts traffic only from http://localhost:4200? It is a web application and obviously I need to allow access from any client coming from anywhere. What changes do I need to make to my code?




Ember filter a list by property name

I have a an array coming from my model..

[
  {id: 1, name: 'test1', created: true}, 
  {id: 2, name: 'test2', created: false}, 
  {id: 3, name: 'test3', created: true}
]

I am interested showing two lists. I created a component to show the list:

../components/created.hbs

<div>
  
</div>


../main.hbs

<h2> Created true </h2>


   



<h2> Created false </h2>


   


The first list would show the the objects with the created property set to true and the second would show those with the created property set to false.

I was wondering if there was a simple way of doing the above in Ember as in Angular where you could use filter pipes inside the each block.




vendredi 27 janvier 2017

Emberjs event Source

When i wrote service and My route model() {

  var chatting=this.get("chatting");

  return this.store.findAll("chatting");
}

I got is

enter image description here

enter image description here

data income but how should i get data from model. data does not come into my model. cannot update




How to query server to retrieve single record / data in ember.js?

I'm trying to get my ember.js app to work.

I have the following code in app/routes/index.js:

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
         // works - it calls the server
         Ember.$.getJSON('http://localhost:20000/Wallet');

         // does not work - server not hit
         this.get('store').findAll('Wallet');

         // this does not work either - server not hit
        this.store.queryRecord('/Wallet', {}).then(function(wallet) {
            //
        });

         // return some dummy data for now
         return 7111;
    }
});

and in my app/adapters/application.js:

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    host: 'http://localhost:20000',
});

the "this.get('store').findAll('Wallet');" method just won't work. (The server does not get hit.)

What's wrong with my code?




Prevent click into component from propagating/bubbling up (ember)

I have an inside of an element that itself has an action.
How do I prevent clicking into the input from triggering the click event on the parent element?

  1. I have tried bubbles=false.
  2. I have also tried extending and in the extended input I caught the click event and called event.preventDefault()

Please try my test case: http://ift.tt/2kvj0Gc

Example hbs:

<div >
  I don't want the click into the input to trigger the div's onlick. Help!<br/>
  
</div>



Ember JS error handling: Accessing errors in model not possible due to adapter error

The version of Ember is 2.10.2.

I asked a question about error responses and handling here: Assertion Failed: `AdapterError` expects json-api formatted errors array

I thought it was solved, but it is not. I can not get my errors to bind (is this a correct way to put it?) it to the model. I now have an adapter error saying:

message:"The adapter rejected the commit because it was invalid"

And the error response looks like this:

{
    "errors": [{
        "source": {
            "pointer": "\/data\/attributes\/email",
            "parameter": null
        },
        "detail": "user.email.not_blank"
    }]
}

Can someone please enlighten me on how to get to the error messages through the model?




Ember store not loading nested hasMany relationship data

I am making a call to an API I built. The response returns a big JSON with all the data nested within it (meaning no need to asynchronously make separate calls for nested related models).

Example:

"feed" : {
  "id": 12345,
  "name": "trogdor",
  "items": [
    {
      "id":6789,
      "content": I am an items content
    },
    {
      "id":6789,
      "content": I am an items content
    },
    {
      "id":6789,
      "content": I am an items content
    },
    {
      "id":6789,
      "content": I am an items content
    }
  ]
}

So as you can see, the Feed model which is return hasMany items.

So my models are defined as such:

Feed Model:

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

Item Model:

export default DS.Model.extend({
  content: attr('string'),
  items: belongsTo('feed')
});

But when the promise is return from my model call, no data is set when I call for the model's "items". Instead I just get a store class with no attributes or data.




In Ember js, periodically check if property has a value

In our project, there's sometime a delay for some data to be provided, in the case fileUrl.

What method in Ember can I use to periodically check that a property has been filled with a value. Then when it's filled, stop the periodic check?

JS (Ember):

import Ember from 'ember';

export default Ember.Controller.extend( {
  licences: Ember.A([
    'Asia',
    'EU',
    'USA'
  ]),

  experimentLicence: 'Asia',

  actions: {
    selectLicence(licence) {
      this.set('experimentLicence', licence);
    },

    saveDataset(model) {
      model.set('licence', this.get('experimentLicence'));

      model.save()
        .then(() => {
          this.send('hideModal');

          /**
           * periodically check if file url is ready to be used
           * Then when file url is ready stop the periodic check
           */
          Ember.run.debouce(() => {
            // check if file url is ready
            if (model.get('fileUrl')) {
              this.send('datasetsIsExportedToMendeleyData', model);
            }
          }); 
        })
        .catch(() => {
          console.log('Oops! Something went wrong. We\'ll fix it as soon as possible.');
        });
    },

    cancel() {
      this.send('hideModal');
    },
  }
});




jeudi 26 janvier 2017

How to store,retrieve and delete data using Ember Data?

am a newbie working with emberJs.

Currently, am developing an ember app that has reached a stage to implement the offline feature where previous data stored has to be accessed while offline.

In my app following code is of one of the templates I use, templates/bbc.hbs:

<img src="/assets/images/bbc-news-icon.png" alt="bbc news logo" style="max-width: 150px;min-height:150px;"> 



<hr>
<div class="panel panel-primary">
<div class="panel-heading"><span class="badge">Title</span>
<h3></h3></div>
<div class="panel-body">
<span class="badge">Description</span>

</div>
<div class="panel-footer"><span class="badge">URL to News</span>
 <a href= target="_blank" role="link" aria-label=>    </a>
 </div>
</div>




and for the above template following is the corresponding route js file, routes/bbc.js

import Ember from 'ember';

export default Ember.Route.extend({
model(){
    return Ember.$.get('http://ift.tt/2jvaMPQ');
}
});

what I need to know is:

1)how to implement the ember data feature so that I could fetch the JSON data while online through this url and store it in a data-store.

2)Retrieve data from data-store to the route js file when the user moves to this route while online/offline.

3)Delete all previous data for that route if selected again while online and update new data received through the Url that receives JSON data. And if Offline just skip this step.

I have already implemented the service-worker with broccoli-serviceworker in this app to implement the offline feature.

Since I didn't find any way to store the data that could be accessed while offline like using IndexedDB feature I think ember data could help.

while asked for a review to my reviewer, he personally suggested me to use Ember Data with the broccoli-serviceworker package to configure a service worker that has access to Embers Data library.

if there is a better option regarding storing and retrieval of data that too with offline compatibility, its welcome.

Please do give a solution with step by step instructions that has to be followed to solve this issue

Github repo link to my project: http://ift.tt/2jkEN1s




Fixing custom authenticator's restore method

I'm using ember-simple-auth and a custom authenticator for an HTTP basic login with CSRF protection. Everything is working fine except sometimes my restore method resolves when it should be failing, like when the session expires.

When authentication succeeds I resolve with the csrf token, but then when the token or session expires and I refresh the page, the resolve method succeeds because all I'm doing is checking if the token is still there (not if it's valid). I know this is wrong, so I guess my question would be what is the proper way to handle this? Should I also be resolving with the session id? Should I be sending an AJAX request in the restore method with the stored token to see if it is still valid and returns success?

Here is my authenticator code:

import Ember from 'ember';
import ENV from 'criteria-manager/config/environment';
import Base from 'ember-simple-auth/authenticators/base';

export default Base.extend({

    restore(data) {
        return new Ember.RSVP.Promise((resolve, reject) => {
            if (data.token) {
                Ember.$.ajaxSetup({
                    headers: {
                        'X-XSRF-TOKEN': data.token
                    }
                });
                resolve(data);
            }
            else {
                reject();
            }
        });
    },
    authenticate(credentials) {
        let csrfToken = this.getCookie('XSRF-TOKEN');
        return new Ember.RSVP.Promise((resolve, reject) => {
            Ember.$.ajax({
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization", "Basic " + btoa(credentials.username + ":" + credentials.password));
                    xhr.setRequestHeader("X-XSRF-TOKEN", csrfToken);
                },
                url: ENV.host + "/api/users/login",
                method: 'POST'
            }).done(() => {
                //A new CSRF token is issued after login, add it to future AJAX requests
                Ember.$.ajaxSetup({
                    headers: {
                        'X-XSRF-TOKEN': this.getCookie('XSRF-TOKEN')
                    }
                });
                Ember.run(() => {
                    resolve({
                        token: this.getCookie('XSRF-TOKEN')
                    });
                });
            }).fail((xhr) => {
                Ember.run(() => {
                    if(xhr.status === 0) {
                        reject("Please check your internet connection!");
                    }
                    else if (xhr.status === 401) {
                        reject("Invalid username and/or password.");
                    }
                    else {
                        reject("Error: Http Status Code " + xhr.status);
                    }
                });
            });
        });
    },
    invalidate() {
        return new Ember.RSVP.Promise((resolve, reject) => {
            let csrfToken = this.getCookie('XSRF-TOKEN');
            Ember.$.ajax({
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-XSRF-TOKEN", csrfToken);
                },
                url: ENV.host + '/logout',
                method: 'POST'
            }).done(() => {
                Ember.run(() => {
                    resolve();
                });
            }).fail(() => {
                Ember.run(() => {
                    reject();
                });
            });
        });
    },
    getCookie(name) {
        let alLCookies = "; " + document.cookie;
        let cookieArray = alLCookies.split("; " + name + "=");
        if (cookieArray.length === 2) {
            return cookieArray.pop().split(";").shift();
        }
    }
});




Send file to Ember controller

In ember index.html i use component to send action and get file

<script type="text/x-handlebars" id="components/picture-upload">
    <input multiple="true" onchange=
    accept="image/png,image/jpeg,application/pdf"
    type="file"
    />
</script>
<script type="text/x-handlebars" id="upload">
    
    
</script>

and in app.js

App.UploadController=Ember.Controller.extend({
  actions:{
    upload:function (event) {
     //here to get file
  }
}});

App.PictureUploadComponent=Ember.Component.extend({
  actions:{
    upload(){
      //i want to send file but this is not good value
      this.sendAction('upload',this);
    }
  }
});

but i don't know how to send event, i need something like this answer,after that i want with ajax to send file to server,but problem is how to get file!




Applying pushObject() to model

This Twiddle is a simple Ember application that tracks the attendance of employees.

It consists of two columns of employee names. On arrival or departure, each employee clicks their name to sign in or out.

The problem is that employees cannot currently sign out.

I'm seeing the error

TypeError: internalModel.getRecord is not a function

for this line

this.get(b).pushObject(item);

I think it's because in this case, b = Ember.computed.alias('model') which isn't an array and therefore pushObject can't be applied. Right?

I suppose I need to know how to map my model to an array or perhaps try a different approach.




Ember incrementProperty throws "cannot convert object to primitive value"

When telling the store to update a record, I get the error: cannot convert object to primitive value

Here is my code, in the route:

this.store.findRecord('track', trackID).then((track) => {
    track.incrementProperty('progress');
});




emberjs component form action

I'm trying to authenticate against DRF token.

I've successfully been able to login using an auth app I have created.

I thought I'd be slick and make the login form a component.

Since making it a component however, I'm not able to login and I get an Assertion failure.

My templates/components/auth-login.hbs template looks like so ...

<form class='navbar-form navbar-right' >
<div class="form-group">


</div>
<button type="submit">Login</button>
</form>

I also have app/controllers/auth-login.js

import Ember from 'ember';

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

  actions: {
    authenticate: function() {
      var credentials = this.getProperties('identification', 'password'),
        authenticator = 'authenticator:jwt';

      this.get('session').authenticate(authenticator, credentials).catch((reason) => {
        this.set('errorMessage', reason.error || reason);
      });
    }
  }
});

It works as an app but not as a component.

If I blank the template, and use the auth route/app instead, it works peachy.




EmberJS change environment variables (e.g. rootURL) at runtime

I need to change the environment variable rootURL at loading time, depending on some global js variable (_ENV), which denotes Symfony's current environment.

So, if accessing the app via http://ift.tt/2k6kIzU it should be rootURL = '/app/'. If accessing via http://somedomain/app_dev.php/app/ it should be rootURL = '/app_dev.php/app/'.

Many thanks!




Ember-DS queryRecord returns TypeError: Cannot convert undefined or null to object

I'm trying to do a queryRecord search inside of my model function and I seem to be hitting an error:

TypeError: Cannot convert undefined or null to object

My model() looks like the following:

model() {
  return this.store.queryRecord('model', { property: 'value' })
    .then(doc => console.log(doc)) // This doesn't even invoke
}




Ember-plupload disable multiple file upload not working

I am using ember 2.5.0.In my application i am having file upload functionality.Using following api Ember-plupload for file upload. Able to upload a file but i want user to upload only one file, as per documentation setting multiple="false" should disable selecting multiple file options, but it is not disabling instead it is adding the file in a queue. Could anyone faced the similar problem?

Also it would be great if some one share the code snippet for removing file from queue.


<div class="form-group">
    <label>Choose file to import</label> <br/>
    <div class="dropzone" id="upload-image" style="width: 80%; height: 100px; border: 2px dashed gray; padding: 0 20px">
        <p>
      <br/>
      <div class="alert alert-success"></div>
        </p>
    </div>
</div>




Ember don't allow bootstrap datetime picker

I have problem with daterange picker and Ember.

On Ember1.10. index.html page on bottom i put

<script type="text/javascript">
 $(function () {
          $('#datetimepicker1').datetimepicker();
            });
 </script>

that works for me, until in random route where i use datarange define model

App.RandomRoute=Ember.Route.extend({
   model:function(){
     return this.store.find('user');
   }})

Problem is when i return some value in model function,

<input type="text" name="daterange" value="01/01/2015 1:30 PM - 01/01/2015 2:00 PM" />

html render this input like normal input type text,don't allow calendar pop-up




What does Ember-simple-auth check againest?

I have been looking for answer of implementing ember-simple-auth (oauth2-password-grant) for days without luck. I use firebase to sign up users, which is successful. However, when in log in page, the action of this.get('session').authenticate('authenticator:oauth2', credentials) seems causing a json error (SyntaxError: Unexpected token < in JSON at position 0) . So my first question is, in theory, how this authentication checks if use email/password is correct? meaning in which file is the "answer" located. Am i supposed to define token? if yes, i already tried "serverTokenEndpoint: 'http://localhost:4200/' or serverTokenEndpoint: 'http://localhost:4200/token" and none works. thanks.




Ember contextual component list

I would like to know if there a way in Ember to have to a parent component keep reference to all contextual components initialized

For example:

In this parent component would have array of 2 child components.


   
   





Ember v. 2.x: watch vendor folder

I'm developing an Ember-JS application with a lot of JavaScript that performs of all kind of UX and styling tasks.

Because these tasks fall out of the scope the MVC-logic, I've put them into modules that I put in the vendor map.

Putting them into the Vendor folder doesn't mean I'm done tweaking these files, but to test them, I'm required to re-start the ember-server over and over again.

How can I make Ember watch these JS-files in my vendor folder and re-compile them when I change them?

The following page answers for Ember v. 1, but doesn't apply to Ember 2.0: http://ift.tt/2kwU4RS

I also tried creating an addon, but ember (cli) answers with: “You cannot use the addon command inside an ember-cli project.”




Ember confused on testing route hooks and actions

I am just starting looking at testing with Ember and I am bit confused on how to test the following:

1 - Route hooks

Here's an example what I have, I am not sure if should be done through unit testing or user acceptance testing? How do I triggers the hooks, wait the promise etc.?

/**
 * Model hook.
 */
model() {
    return this.modelFor('new');
},

/**
 * AfterModel hook.
 */
afterModel() {
    /**
     * Setup provinces.
     */
    return new Ember.RSVP.Promise((resolve) => {
        const provinces = Ember.A([
            Ember.Object.create({
                code: 'AB',
                description: 'Alberta'
            }),
            Ember.Object.create({
                code: 'BC',
                description: 'British Columbia'
            }),
            Ember.Object.create({
                code: 'MB',
                description: 'Manitoba'
            }),
            Ember.Object.create({
                code: 'NB',
                description: 'New Brunswick'
            }),
            Ember.Object.create({
                code: 'NL',
                description: 'Newfoundland and Labrador'
            }),
            Ember.Object.create({
                code: 'NS',
                description: 'Nova Scotia'
            }),
            Ember.Object.create({
                code: 'NT',
                description: 'Northwest Territories'
            }),
            Ember.Object.create({
                code: 'NU',
                description: 'Nunavut'
            }),
            Ember.Object.create({
                code: 'ON',
                description: 'Ontario'
            }),
            Ember.Object.create({
                code: 'PE',
                description: 'Prince Edward Island'
            }),
            Ember.Object.create({
                code: 'QC',
                description: 'Quebec'
            }),
            Ember.Object.create({
                code: 'SK',
                description: 'Saskatchewan'
            }),
            Ember.Object.create({
                code: 'YK',
                description: 'Yukon'
            })
        ]);
        resolve(provinces);
    }).then((provinces) => {
        this.set('provinces', provinces);
    });
},

/**
 * Setup controller hook.
 * @param controller the controller
 * @param model The model
 */
setupController(controller, model) {
    this._super(controller, model);
    controller.set('provinces', this.get('provinces'));
}

2 - Controller/Route Actions

Here I mostly just either going to different route or displaying error message, is this something that should be unit tested? if so how?

actions: {
    /**
     * Go previous step
     */
    back() {
        this.transitionToRoute('new.step1');
    },
    /**
     * Go to next step.
     */
    next() {
        this.get('model').save().then(() => {
            this.transitionToRoute('new.step3');
        }).catch(() => {
            this.get('notificationService')
                .notifyError('common.error.system_error');
        });
    }
}




Allow binding to any data-* attribute on an ember component

I am designing a library whereby I would like to allow the user to supply any data attributes they might like.

I don't know ahead of time which data attributes they might like to bind to so can't add them to the attributeBindings array.

Is there a workaround for this?




Assertion Failed: `AdapterError` expects json-api formatted errors array

After reading Handling Errors with Ember Data and numerous other tips and tricks on how to solve error handling in Ember JS, I still am not able to figure out what is wrong with my code.

For starters, I have a user model like so:

import DS from 'ember-data';

export default DS.Model.extend({
    firstName: DS.attr('string'),
    surName: DS.attr('string'),
    email: DS.attr('string'),
    plainPassword: DS.attr('string')
});

Obviously I do not return a password from the server, but I assume it is needed in the model to send it from the registration form. Anyway, onward.

The form template looks like this:

<!-- start Register -->
<div class="container-fluid">
    <form name="form_register"  class="form-register" novalidate="novalidate">
        <div class="col-md">
            <label class="el-input-wrap">
                First Name
                
            </label>
            <label class="el-input-wrap">
                Last Name
                
            </label>
        </div>
        <div class="col-md">
            <label class="el-input-wrap">
                Email
                
            </label>
            <label class="el-input-wrap">
                Password
                
            </label>
        </div>
        <div class="col">
            <label class="el-checkbox">
                By registering I agree to the terms and conditions
            </label>
        </div>
        <button type="submit" class="el-btn mod-full-w">REGISTER</button>
    </form>
</div>
<!-- end Register -->

Next I have the registration controller that handle the registration form:

import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        cancel() {
            this.get('model').deleteRecord();
            return true;
        },

        submit() {
            var user = this.get('model');
            user.save().then(
                () => this.transitionToRoute('register')
            ).catch((adapterError) => {
                console.log(adapterError);
            });
        }
    }
});

Here, I have tried to console.log errors, errors.firstName and so on. But no errors show.

The adapterError tells me the error format is not in JSON API format. But from what I can see, it is:

{
    "errors": {
        "source": {
            "pointer": "user\/email"
        },
        "detail": "user.email.not_blank"
    }
}

Lastly, I am using the RESTAdapter in adapters/application.js:

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.RESTAdapter.extend(DataAdapterMixin, {
    namespace: 'app_dev.php/api',
    authorizer: 'authorizer:token', //or authorizer: 'authorizer:jwt'
});

For the life of me, I can not figure out what is wrong. I would very much appreciate any help or pointers. Thank you.




mercredi 25 janvier 2017

Ember data belongsTo relationship saving, but results not visible in a template

I can successfully save a belongsTo relationship, but am not able to see the result in a template.

I cannot seem to populate the belongsTo record - no query is sent to my server to resolve the relationship.

The returned json shows a user_id - but ember is not able to use that to establish the belongs to record.

My question is, how do tell ember to use the user_id in the returned json to establish the belongsTo relationship?

I have 2 models

User

import DS from 'ember-data';

export default DS.Model.extend({
  email:       DS.attr('string'),
  firstName:   DS.attr('string'),
  lastName:    DS.attr('string’)
});

support-request

import DS from 'ember-data';

export default DS.Model.extend({
  user:     DS.belongsTo('user', { async: false }),
  category: DS.attr('number'),
  status:   DS.attr('number'),
  serviceLevel: DS.attr('number'),
  message:  DS.attr('string')
});

This is support-requests/index.js router

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

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

export default Ember.Route.extend(AuthenticatedRouteMixin, {

  metaParams: {
    meta: {
      refreshModel: true
    }
  },

  model: function(params) {
    return this.store.query('support-request', params);
  },

});

A successful request is made to: http://localhost:3003/api/rest/support_requests

Which returns 1 record

meta : {total: 1, offset: 0, limit: 0}

support_requests : [
 category : 1
 created : "2017-01-25T08:50:10.588Z"
 id : "588866c24f2a9acd6bfa66e3"
 images : []
 message : "asdfasdf"
 modified : "2017-01-25T08:50:10.599Z"
 service_level : 3
 status : 2
 support_actions : []
 **user_id : "58044e4b7fc427faf6cfe4f9"**
]

Inside my template I have

    
      
      <tr >
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>
         Edit
        </td>
      </tr>
    

All the supportRequest variables are shown, but the supportRequest.user is empty and does generate a server request to populate the data.




Ember store returns class containing model data but not model instance

I am trying to use ember's store to send requests to the api for data. I am so close to getting it working, but for some reason, the model data doesn't display in the template.

I get a response back from the server which looks like this:

artist_profile: {
   alias:"alias",
   bio:"biofda",
   created_at:Tue Nov 22 2016 10:50:27 GMT-0500 (EST),
   location:"location",
   portfolio_link:"link",
   updated_at:Thu Dec 22 2016 20:55:38 GMT-0500 (EST)
}

But when it goes through the serializer, it is set on the model like this:

Route model:

...
data: {
  alias:"alias",
  bio:"biofda",
  created_at:Tue Nov 22 2016 10:50:27 GMT-0500 (EST),
  location:"location",
  portfolio_link:"link",
  updated_at:Thu Dec 22 2016 20:55:38 GMT-0500 (EST),
},
id:"980190976",
...

I think this is why it is not rendering properly on the template. In fact if i debugger into the route and call this.model.alias, it is returned as undefined. but if i do route.get('model').get('alias'), it returns the alias value.

Anyone know what I'm doing wrong to prevent the store from properly returning a model that the template can render?

More code:

Adapter:

 export default DS.RESTAdapter.extend({
    host: CONFIG.API_HOST,
    pathForType() {
      return 'artist_profiles';
    }
  });

Serializer:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) {
    payload = { artist_profiles: payload.artist_profile };
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

Model class:

import DS from 'ember-data';

const {
  Model,
  attr,
  belongsTo
} = DS;

export default Model.extend({
  alias: attr('string'),
  bio: attr('string'),
  portfolio_link: attr('string'),
  location: attr('string')
});

Route model hook:

model() {
  return this.get('store').find('artist-profile', 980190976);
}

Template:

ARTIST PROFIlE <br>










Firebase Security Rules Emberfire Multiple Access Levels Per Node

I have two Ember models: a items and comments. User will post an item, and other users will be able to comment on the items.

I cannot setup security rules within firebase that allow name and description to be writable by only the current user, but allow for comments to be written to by any logged in user.

Item

// app/models/item.js
export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  comments: DS.hasMany('comment'),
  user: DS.belongsTo('user')
})

Comment

// app/models/comment.js
export default DS.Model.extend({
  user: DS.belongsTo('user')
  body: DS.attr('string'),
  timestamp: DS.attr('string'),
  item: DS.belongsTo('user')
})

Saving a comment

// app/components/comment-form.js
const comment = this.get('comment');
const item = this.get('item');
// service that tracks the currently logged in user
const currentUser = this.get('sessionManager.user');
comment.set('timestamp', new Date());
comment.set('user', currentUser);

// setup both sides of the relationship
item.get('comments').pushObject(comment);
comment.set('item', item');

// save both
return Ember.RSVP.Promise.all([item.save(), user.save()]);

All this works fine. Today, I added security rules in firebase. I only want the currently logged in user to be able to edit an item, but allow any other user to add a comment to any item.

"items": {
    ".read": "auth !== null",
    "$item_id": {
        // only the currently logged in user can write to this node
        ".write": "root.child('users/'+data.child('user').val()+'/uid').val() === auth.uid",
        // allow any user to write comments
        "comments": {
            ".write": "auth !== null"
        }
    }
},

In the firebase simulator this works. As the user who owns the item I can write to /items/<item_id>/description. As a user who does not own the item, I can write to /items/<item_id>/comments/, but not to /items/<item_it>/description. However it fails within Ember using Emberfire.

My working theory is that when I add a new comment to an item I do not "own", then I call item.save() Emberfire tries to write to /items/<item_id>.

How can I setup Firebase security rules such that only the user who owns the item can update most of its properties, but any user can add a comment




radio button in handlebars

Is there possibility in handlebars to do something like Admin Guestproperty of model, model.isAdmin return true or false. Because handlebars version is 1.3.0. answer on this question doesn't help me!




Emberjs site size issue

I have created app using emberjs file, but my app.js file is more 3.2 MB after build which take time to load and site is becoming slow. Can you please suggest how I can decrease size of site ?

I am also thinking to move the code to Reactjs. So please suggest what should I do.




Ember file upload while clicking button

I am facing 2-issues while working on file-upload using Ember 2.5.0.

I using Ember-plupload for file uploading. I can able to upload the file but the upload is happening whenever i drag and drop the file, My requirement is,I am having a form and file upload which will let user to select or drag the required file and fill the sufficient information after that user will click the "Import" button.While clicking the import button only i have to upload the file and other informations.

Issue 2: Is it possible to send request parameters via URL instead of appending in the URL ?

index.hbs


<div class="dropzone" id= style="width: 80%; height: 100px; border: 2px dashed gray; padding: 0 20px">

  
      Drop to upload
  
      Invalid
  

    Uploading  files. (%)

    <h4>Upload Images</h4>
    <p>
      
          Drag and drop images onto this area to upload them or
      
        <a id="upload-image">Add an Image.</a>
    </p>

</div>
    

Route.js

uploadImage: function (file) {
  file.upload('/api/v1/book/import').then(function (response) {
      console.log("response",response);
      //set(image, 'url', response.headers.Location);
      //return image.save();
    }, function (err) {
      console.log("error",err);
      //image.rollback();
    });
  }

Your help should be appreciated.




ember crash from heroku-buildpack-static configuration in static.json

Recently, I learned how to make a rails and ember-cli app talk to one another thru these tutorials. Following these tutorials and got a rails-5 API-mode app (running on localhost:3000) and an ember app (running on localhost:4200) to talk to one another thru rails "active-model-seralizer" gem and embers "active-model-adapter" package.

Currently, I am trying to deploy these small rails and ember apps on heroku. The rails app deployed just fine and is sending JSON at a /monsters endpoint. The exact url that is sending this json is here http://ift.tt/2jxt3JR

For context this is what my embers-cli app/routes/application.js, which should consume this JSON, looks like

import Ember from 'ember';

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

This is my ember monser.js model

import DS from 'ember-data';

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

My ember application.js

import ActiveModelAdapter from 'active-model-adapter';

export default ActiveModelAdapter.extend();

And, finally, my my ember application.hbs

<h1>Hello World</h1>
<ul>

  <li> is level </li>

</ul>

However, I am having problems getting my deployed ember app to proxy its AJAX calls to my deployed rails server. When I was running my ember app locally I could specify its proxy to localhost:3000 and it ran perfectly. But now that it and the rails app are being deployed, I'm having problems getting the ember app to proxy correctly. I have been trying to update its proxy settings by following the documentation found here.

My approach has been to add a static.json file at the root of my ember-cli app that looks like this

{
  "root": "dist/",
  "proxies": {
    "/": {
      "origin": "http://ift.tt/2jxgYnY"
    }
  }
}

This configuration, however, breaks my ember app. When looking through my heroku logs I see this error

2017-01-25T02:34:16.533811+00:00 app[web.1]: Starting nginx...
2017-01-25T02:34:16.554911+00:00 app[web.1]: nginx: [emerg] duplicate location "/" in ./config/nginx.conf:64
2017-01-25T02:34:16.555713+00:00 app[web.1]: Process exited unexpectedly: nginx
2017-01-25T02:34:16.555900+00:00 app[web.1]: Going down, terminating child processes...
2017-01-25T02:34:16.674333+00:00 heroku[web.1]: State changed from starting to crashed
2017-01-25T02:34:16.640841+00:00 heroku[web.1]: Process exited with status 1

Which makes me believe that there's something wrong with my static.json configuration. What do I need to change in order for my deployed ember app to treat my deployed rails as its proxy?




Ember data store object not rendering through template

I am trying to use ember's store to send requests to the api for data. I am so close to getting it working, but for some reason, the model data doesn't display in the template.

I get a response back from the server which looks like this:

artist_profile: {
   alias:"alias",
   bio:"biofda",
   created_at:Tue Nov 22 2016 10:50:27 GMT-0500 (EST),
   location:"location",
   portfolio_link:"link",
   profile_img_url:"http://ift.tt/2jxlWRN",
   updated_at:Thu Dec 22 2016 20:55:38 GMT-0500 (EST)
}

But when it goes through the serializer, it is set on the model like this:

Route model:

...
data: {
  alias:"alias",
  bio:"biofda",
  created_at:Tue Nov 22 2016 10:50:27 GMT-0500 (EST),
  location:"location",
  portfolio_link:"link",
  profile_img_url:"http://ift.tt/2jxlWRN",
  updated_at:Thu Dec 22 2016 20:55:38 GMT-0500 (EST),
},
id:"980190976",
...

I think this is why it is not rendering properly on the template. In fact if i debugger into the route and call this.model.alias, it is returned as undefined. but if i do `route.get('model').get('alias'), it returns the alias name.

Anyone know what I'm doing wrong to prevent the store from properly returning a model that the template can render?

More code: Adapter:

 export default DS.RESTAdapter.extend({
    host: CONFIG.API_HOST,
    pathForType() {
      return 'artist_profiles';
    }
  });

Serializer:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) {
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

Model class:

import DS from 'ember-data';

const {
  Model,
  attr,
  belongsTo
} = DS;

export default Model.extend({
  alias: attr('string'),
  bio: attr('string'),
  portfolio_link: attr('string'),
  location: attr('string'),
  profile_img_url: attr('string')
});

Route model hook:

model() {
  return this.get('masterService').loadTracks();
}

Template:

ARTIST PROFIlE <br>










While using a component multiple times how to trigger or detect all the component at once - Ember

I have created a custom component which allows user to type and also select from a dropdown. The dropdown is a dynamic div. I have managed to close all the open dropdown on clicking outside of the dropdown.But if i click a component dropdown while the other component if the dropdown is open is not getting closed. I tried to make a common model/variable and enable it only on click but it dint work. Below are my HBS and JS files

custom-dropdown.hbs

<div class="custom-dropdown">
<div class="cus-drop-text">
    
</div>
<div class="cus-drop-img" >
    <div class="overlapDiv" >
    </div>
    <select id=  class="pull-left editableDDSelect">
    
        <option value="" hidden></option>
    
    </select>
</div>
        
<div class="cus-drop-list " id="cus-drop-list">
    
    
        <span class='active cus-drop-list-item'   data-value=></span>
        
        <span class='cus-drop-list-item'   data-value=></span>
    
    
</div>


custom-dropdown.js

import Ember from 'ember';
export default Ember.Component.extend({
 inputName:"",
 dropdownDD: "",
 dropdownTF: "",
classNameBindings: ['isShowing'],
isShowing: 'visible',
showList:false,
hidealways:false,
isActive:false,
selectedValue: "",
inputValue:"",
didInsertElement() {
    var self=this;
    var clickFunction = function (event) {
        var target = Ember.$(event.target);
        if(target.context.className !== "overlapDiv"){
            if(!self.isDestroyed){
            self.set('showList',false);
            }
        }
    };
    window.addEventListener("click", clickFunction, false);
},

didReceiveAttrs() {
    this.set('inputName',this.get('inputID'));
    this.set('dropdownName',this.get('dropdownID'));
    this.set('dropdownTF',this.get('inputName')+"TF");
    this.set('dropdownDD',this.get('dropdownName')+"DD");       
    this.set('inputValue',this.get('value'));
},
keyPress(event){        
    this.validateInput(event);
},    

validateInput(event) {
    switch(this.get('allowedText')){
        case "numOnly":
            // Allow: backspace, delete, tab, escape, enter and numbers
            if (Ember.$.inArray(event.keyCode, [8, 9, 13, 27, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57]) !== -1 ||
            // Allow: Ctrl+A, Command+A
            (event.keyCode === 65 && (event.ctrlKey === true || event.metaKey === true))) {
            // let it happen, don't do anything     
                if(Ember.$("#"+this.elementId+"TF").val().length  < this.get('allowedCharLen')+1){
                return;
                }
                else{   
                event.preventDefault();
                }
            }
            else{   
                event.preventDefault();
            }
        break;

    }
},   
actions:{
    focusOutFire:function(){
        var self =this;
        self.set('showList',false); 
    },
    onOptionChange:function(selectedValue){ 
        var self = this;
        self.set('selectedValue',selectedValue);
        self.set('showList',false); 
        self.set('inputValue',"");
        self.set('inputValue',selectedValue);
    },
    showList:function(){
        var self =this;         
        var showDropdown = true;
        // To check if the dropdown is enabled or disabled
        if(Ember.$("#"+this.get('dropdownID')+"DD").is(":disabled")){
            showDropdown = false;
        }
        else{
            showDropdown = true;
        }

        if(showDropdown){
            if(self.get('showList')){
                // Disabled Dropdown so don't show the list on click
                self.set('showList',false); 
            }
            else{
                // Dropdown is enabled                  
                self.set('showList',true);  
            }
        }
    }
}

});

enter image description here

Check the attached image. I want to close the already opened dropdown when clicking the other dropdown. Also suggest best practice to improve my ember coding in this component. Thank you for your help




ember generate cordova-init throwing EPERM error

I'm trying to run sample which is given in docs/getting started, but consistently throwing the following error (tried with different windows box). ember generate cordova-init com.poeticsystems.hello --platform=android

Path: platforms\android
Package: com.poeticsystems.hello
Name: Hello
Activity: MainActivity
Android target: android-25
Subproject Path: CordovaLib
Android project created with cordova-android@6.1.1
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it to the
project
Fetching plugin "cordova-plugin-whitelist@1" via npm
Installing "cordova-plugin-whitelist" for android

    This plugin is only applicable for versions of cordova-android greater
    than 4.0. If you have a previous platform version, you do *not* need
    this plugin since the whitelist will be built in.

Adding android platform to cordova...
Update config.xml with your project settings...EPERM: operation not
permitted, symlink '..\dist' -> 'N:\DEV\ember-cordova\hello\cordova\www'
Error: EPERM: operation not permitted, symlink '..\dist' -> 'N:\DEV\ember
cordova\hello\cordova\www'
at Error (native)

os: win32 x64 node - 4.4.2 npm - 2.15.0 ember-cli: 2.4.3 cordova - 6.5.0 ember-cli-cordova: 0.1.0-beta-2

I have modified value of locationType to 'hash'. Could anyone please help to resolve this.




mardi 24 janvier 2017

jQuery library not loading in Ember

I am using jPlayer inside my application. I have a component called player-button in which I create the jPlayer.

export default Ember.Component.extend({
  didInsertElement: function () {
    Ember.run.scheduleOnce('afterRender', this, function () {
      console.log(this);
      Ember.$("#jquery_jplayer_1").jPlayer({
        ready: function () {
          $(this).jPlayer("setMedia", {
            title: "Bubble",
            m4a: "http://ift.tt/1rgfaht",
            oga: "http://ift.tt/1nvykNf"
          });
        },
        cssSelectorAncestor: "#jp_container_1",
        supplied: "m4a, oga"
      });
    })
  }
});

On my template called station I have it render a button that will start the playback.

For some reason if I open the page at the /station endpoint the player loads fine, but if I navigate from /home to /station it tells me $(...).jPlayer is not a function

Why is this?




How can I dynamically set the `selected` attribute on an `` tag?

The Ember guide on binding data attributes says that "If you use data binding with a Boolean value, it will add or remove the specified attribute." I'm trying to use this feature to dynamically set the selected attributes on <option>s. I'm finding that I can dynamically set the disabled attribute, but the selected attribute is always omitted, no whether the boolean is true or false.

Given this handlebars template:

<option disabled=false selected=false>One</option>
<option disabled=true selected=true>Two</option>

I get the following HTML:

<option>One</option>
<option disabled>Two</option>

Why doesn't selected=true produce a selected attribute in the rendered output?


To give a bit more context, I'm following this article on How to do a select in Ember 2.0. Using the method described in that article, I can successfully update the data in the controller when the select onchange event fires, but the DOM doesn't update to reflect the change.

I've put together this ember-twiddle, which includes two select elements. One uses select=, which doesn't work the way I want it to. The other uses a long-hand ......, which does work but looks terrible.




route.afterModel hook not being hit

The afterModel hook is not being hit when you attempt to transitionTo from a parent route to the same route.

I expected the afterModel hook to always fire.

Twiddle