mercredi 30 septembre 2015

Webpack ember-templates-loader

does webpack ember-templates-loader loads all templates (*.hbs) automatically into Ember.TEMPLATES, or do I need to explicitly write require('ember-templates!./templates/my-view.hbs') into my code before bundling?

Thanks.




Rails + Emberjs: Can't verify CSRF token authenticity

I'm new to using rails as an api with an Emberjs front-end. I'm getting a 'Completed 422 Unprocessable Entity' and Can't verify CSRF token authenticity whenever I try to do a POST request

I've seen a couple of posts and solutions saying to insert this function

$(function() {
    var token = $('meta[name="csrf-token"]').attr('content');
    return $.ajaxPrefilter(function(options, originalOptions, xhr) {
        return xhr.setRequestHeader('X-CSRF-Token', token);
    });
});

Where is the appropriate place to implement CSRF in an ember-cli project?




How to check for dirty changes made to a model in ember js

I have a object when any of the value to the keys inside the object changes I want to update a computed property. Is there a way to observe the value changes of an object with computed property.




Wait for ApplicationRoute to resolve before going to a child route

To explain the issue I'm facing, I have 2 routes : ApplicationRoute and SomeRoute. I would need to wait for ApplicationRoute to resolve before trying to do something with SomeRoute.

The call order I see in debug :

ApplicationRoute.model // which returns a promise
SomeRoute.model
SomeRoute.setupController
ApplicationRoute.setupController

What I would want :

ApplicationRoute.model // which returns a promise
ApplicationRoute.setupController
SomeRoute.model
SomeRoute.setupController

There's probably a detail I'm missing somewhere...




Is it possible to compile an Ember-cli application as a native Windows Application?

Is there any compiler capable of compiling an ember-cli application as a native Windows application? If so, is there any plugin to get access to the windows API, filesystem, DLL, etc in this case?




Best practices for the input helper in new Ember components

I'm currently learning about Ember's new data-down, actions-up paradigm for components. As discussed here, however, sometimes I want to allow the child component to modify the property explicitly. This is where the mut helper comes in: it creates a wrapper for the passed in value, containing a (readonly?) value and a function to update it. The example on that page is for a simple button which increments a counter.

How does this concept work if I'm using the input helper inside a component? For example, let's say I'm building a form which consists of a bunch of special form components:

// templates/index.hbs
<form>
    {{form-control value=(mut model.firstValue)}}
    {{form-control value=(mut model.secondValue)}}
</form>

If the form-control component just has the task of wrapping the input control, how do we use the passed-in mut object correctly? Is it something like?

// templates/components/form-control.hbs
{{input type="text" value=attrs.value.value input=attrs.value.update}}

My thinking here: the value of the input element is set to the value of the mut object, and whenever the input value changes (HTML5 input event) the update method of the mut object is called to set the model property to the new value. It seems there's something wrong with my thinking though, because this doesn't work. What is the "standard" way of doing this now? I'm using Ember 1.13.8.




findAll events with ember-data

I'm very new in Ember world, and I'm struggling myself to make ember data work, but errors always happen.

I want get all my events with this.findAll('events'); in my events route, i already setup everything right i think.. but still not working.

Currently two errors is appearing.

1:

WARNING: Encountered "data" in payload, but no model was found for model name "datum" (resolved model name using SiteApp.ApplicationSerializer.modelNameFromPayloadKey("data"))

2:

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

I'm not getting where i'm messing up.

This is all i have:

Ember initialization.

window.SiteApp = Ember.Application.create({
  LOG_TRANSITIONS: true
});

Configuration of RestAdapter and RestSerializer:

SiteApp.ApplicationAdapter    = DS.RESTAdapter.extend({
  namespace: 'api
});
SiteApp.ApplicationSerializer = DS.RESTSerializer.extend({
  primaryKey: '_id'
});

Events router:

SiteApp.EventsRoute = Ember.Route.extend({
  model: function() {
    this.store.findAll('events');
  }
});

Events model:

SiteApp.Events = DS.Model.extend({
  _id         : DS.attr(),
  date        : DS.attr(),
  description : DS.attr(),
  hiw         : DS.attr(),
  hour        : DS.attr(),
  meeting     : DS.attr(),
  men         : DS.attr(),
  name        : DS.attr(),
  title       : DS.attr(),
  women       : DS.attr(),
  created_at  : DS.attr(),
  is_active   : DS.attr(),
  updated_at  : DS.attr()
});

So, when i access the route /api/events, this is the JSON format that i'm going receive:

{
  data: [{
    _id: "55f660bdd80a0fd2e298f333",
    title: "Pubx",
    date: "2015-09-05T03:00:00.000Z",
    created_at: "2015-09-14T05:53:01.292Z",
    __v: 0,
    updated_at: "2015-09-14T13:34:52.780Z"
  }, {
    _id: "55f660bdd80a0fd2e298f335",
    title: "Pub",
    date: "2015-09-05T03:00:00.000Z",
    created_at: "2015-09-14T05:53:01.610Z",
    __v: 0
  }, {
    _id: "55f660bdd80a0fd2e298f336",
    title: "Pub",
    date: "2015-09-05T03:00:00.000Z",
    created_at: "2015-09-14T05:53:01.769Z",
    __v: 0
  }, {
    _id: "55f660bdd80a0fd2e298f337",
    title: "Pub",
    date: "2015-09-05T03:00:00.000Z",
    created_at: "2015-09-14T05:53:01.943Z",
    __v: 0
  }, {
    _id: "55f6cc55f8aeb32de86a88e9",
    date: "2015-09-15T00:00:00.000Z",
    created_at: "2015-09-14T13:32:05.477Z",
    __v: 0
  }]
}

I already search a lot and i just cant figure out what is the problem here, i'm not seeing where is the problem.. :/

Thanks very much!


UPDATE:

I'm using:

"ember": "~2.0.2",
"ember-data": "~2.0.1",
"jquery": "^1.11.3"




User ActiveModelAdapter to make arbitrary JSON query in ember

I'm using the standard ActiveModelAdapter in my Ember app to do most of my queries to work with Ember model object.

In one case, however, I want to make a arbitrary REST request to get back JSON to populate a chart (not backed by a model) but I want to go "through" the ActiveModelAdapter so the correct host values are used.

Here's what's not working:

updateChartFromIndustry: function() {
  Ember.$.ajax({
    context: this,
    method: 'get',
    url: 'api/v3/charts/all_risk.json',
    dataType: 'json',
    data: { ind: this.get('ind') }
  }).then(function(json) {
      Ember.$('#risk-days-data').highcharts(json);
    },
    function(errs) {
      console.log(errs);
    }
  );
}.observes('ind'),

In development, that query goes to localhost:4200 (the ember server) rather than the rails backend at localhost:3000. Explicitely setting the full URL makes the query go through but without the various user session informatino that authenticates the request.

I'm really hoping for something simple like:

this.store.query('arbitrary url and params', ....)

as if I were making a normal query for a model or, alternately, to leverage the adapter:

Ember.adapter.$.ajax(....) 




Passing an array as a query parameter to the link-to helper

I have a queryParam in my controller that is an array like so:

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

  // Other code goes here
}

Now I want to link to this controller and provide one or many values to the customFilters queryParam as an array like so:

{{#link-to 'search' (query-params customFilters=['selection1'])}}
  Custom Selection
{{/link-to}}

Unfortunately the link-to helper doesn't seem to allow me to do that and just gives me a link to the search route with no query parameters. So I have two questions.

1) Is this something that I should be able to do? 2) Can I use the link-to helper to generate the link for me or should I try and hand roll it?




How do you update a controller from another controller in ember.js?

In my application I have common header that outlets into the main application layout. In that header you can select a site. I need that site selection to update another template that is rendered in the application layout. Having struggled with this for a few days I think the correct way to solve this is to use a shared service, to have the header controller observe the site selection and set that value in the shared service, then to have the index controller use a Ember.computed.alias on the value in the service controller. The following is an example of my code:

controllers/header.js

import Ember from 'ember';

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

  currentSiteChanged: Ember.observer('session.current_site', function(){
    var current_site = this.get('session.current_site');
    console.log('currentSiteObserver', current_site);
    this.get('sessionService').set('currentSite', current_site);
  }),

});

controllers/index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  sessionService: Ember.inject.service(),
  currentSite: Ember.computed.alias('sessionService.currentSite'),
  dashboardData: function(){
    var currentSite = this.get('currentSite');
    console.log("in dashboardData", currentSite);
    //other code that uses the currentSite
  }.property('currentSite'),
});

services/session-service.js

import Ember from 'ember';

export default Ember.Service.extend({
  currentSite: null,

  setCurrentSite: function(){
    var currentSite = this.get('session.current_site');
    this.set('currentSite', currentSite );
  }.on('init'),
});

I think this should allow someone to select a site in the header and have the dashboardData property in index update to use that selection. When the page initially loads the header defaults to the first site and the index renders it has the correct site value that it must have gotten from the session-service, however if you select another site the index does not get updated. Via the console.logs and debugging I can see that the header is observing the change and setting the value on the session-service.

Additionally I have tried solving this other ways (injecting the header service into the index and observing a property, injecting the index in the header and directly setting the value, sending and listening to events,etc) but I am willing to try anything or to be corrected that this isn't the correct way to solve the problem.

I am using ember 1.13.8 and moving to 2 isn't an option at the moment.




Ember 2, model.save() from component my-modal.hbs

I have this posts.hbs:

{{#each model as |post|}}
    <a href="#" {{action 'openWriteModal' post}}>

      <h3>{{post.title}}</h3>
          {{post.text}}
          {{post.author.name}}
    </a>
{{/each}}

Then I open my write-modal.hbs:

{{input value=model.title size="40" escape-press='close'}}

{{model.author.name}}

{{input value=model.text size="70" escape-press='close'}}

<button {{action 'close'}}>Close</button>
<button {{action 'save' model}}>Save</button>

Now, this is my components/write-modal.js:

export default Ember.Component.extend({

  actions: {

    close: function() {
      return this.sendAction('close');
    },

    save(model) {
        model.set("text", model.get("text"));
        model.save().then(this.sendAction('close'));
    }
  }
});

here is the posts.js:

export default Ember.Route.extend({

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

  actions: {
    openWriteModal(post) {

      return this.render('modal', {
        outlet: 'modal',
        into: 'application',
        model: this.store.findRecord('post', post.id, { reload: true }),
        controller: 'application'
      });
    },

    closeWriteModal() {

      return this.disconnectOutlet({
        outlet: 'modal',
        parentView: 'application'
      });
    },

    saveWriteModal(model) {

      model.save();
},

......

  model(params) {
    return this.store.query('post', params);
  }

});

in my application.hbs:

{{outlet}}

{{outlet "modal"}}

and finally modal.hbs:

{{write-modal model=model close='closeWriteModal' save='saveWriteModal'}}

but I got this error: "Uncaught TypeError: Cannot read property 'save' of undefined"

How to fix this?




ember.js best practice for commenting actions

I could not find any real info on this.

What is the best practice for commenting actions, methods in ember.js component.

Is there an example ?

thanks




Each is not working as supposed with Handlebar

In an app that use Handlebar 4.0.3, I have this simple template :

{{#each certificates}}
  <tr>
    <td data-title='Certification'>{{this}}</td>
  </tr>
{{/each}}

And I use compile it like this :

result = template(certificates: ['test'])

I have this result :

<table class="table table-hover table-condensed tablesorter">
  <tbody><tr>
    <td data-title="Certification">[object Object]</td>
  </tr></tbody>
</table>

I think I should have "test" instead of "[object Object]".

I tried with this template :

{{#each certificates}}
<tr>
  <td data-title='Certification'>{{this}}</td>
  <td data-title='Certification'>{{name}}</td>
</tr>
{{/each}}

And this JavaScript :

result = template({ certificates: [{name: 'Name'}]})

And I have tyhis result :

<table class="table table-hover table-condensed tablesorter">
  <tbody><tr>
    <td data-title="Certification">[object Object]</td>
    <td data-title="Certification"></td>
  </tr></tbody>
</table>

As you can see, {{name}} gives nothing instead of "Name".

Am I doing something wrong?




Ember add multiple models to router with different endpoints

Question about routes and adapters. I have two different models ‘merchants’ which i get at '/merchants/1234' and 'products tags’ which I get at ‘merchants/1234/product_tags’. There is no links in the JSON in the merchant request to the associated product_tags.

I want both of these models to exist in the router 'Merchants', I get how to add multiple models to the router, but does anyone have a suggestion on how to get the second (product_tags) which is a slightly different URL setup within the adapter?




Feed ember-collection with store.query result

I fetch a list of ingredients using this computed property:

results: Ember.computed('searchQuery', function() {
  return this.store.query('ingredient', { filter: searchQuery, limit: 150 });
}

Then I can iterate trough the results usin:

{{#each results as |result|}}
  {{result.name}}
{{/each}}


Now I'd like to use {{ember-collection}} but when I try to use it as follow:

{{#ember-collection
  items=results
  width=800
  cell-layout=(fixed-grid-layout 800 50) as |item index|
}}
  {{name}}
{{/ember-collection}}

the ember-collection component displays just an empty list.

What am I doing wrong?




Can we route on a multiple route without changing the url ? Like background execution of each route

I am new in ember.js.

I five different templates with its dynamic data. I have to get all the template html with data and use for the pdf generation.

I have try it in for loop to process this but with route change url is also change in the browse.

Can we able to process all the route without changing the url on browser like a background execution of all the routes and get it's html from templates with data ?




Ember 2, model.save() from component my-modal.hbs

I have this posts.hbs:

{{#each model as |post|}}
    <a href="#" {{action 'openWriteModal' post}}>

      <h3>{{post.title}}</h3>
          {{post.text}}
          {{post.author.name}}
    </a>
{{/each}}

Then I open my write-modal.hbs:

{{input value=model.title size="40" escape-press='close'}}

{{model.author.name}}

{{input value=model.text size="70" escape-press='close'}}

<button {{action 'close'}}>Close</button>
<button {{action 'save' model}}>Save</button>

Now, this is my components/write-modal.js:

import Ember from 'ember';

export default Ember.Component.extend({

  actions: {

    close: function() {
      return this.sendAction('close');
    },

    save(model) {
        model.set("text", model.get("text"));
        model.save().then(this.sendAction('close'));
    }
  }
});

but I got this error: "Uncaught TypeError: model.save is not a function"

How to fix this?




Backend Validation with RESTAdapter always "The adapter rejected the commit because it was invalid"

Configuration

  • Backend = Laravel 5.1, with Dingo API
  • Frontend = Ember 1.13.6, Ember Data 1.13.7
  • Adapter = Ember Data RESTAdapter

The Problem

I'm trying to handle backend validation errors on my first Ember application. When errors are returned from the server, I get this error:

Error: The adapter rejected the commit because it was invalid
at new Error (native)
at Error.EmberError (http://localhost:4200/assets/vendor.js:26266:21)
at Error.ember$data$lib$adapters$errors$$AdapterError (http://localhost:4200/assets/vendor.js:69564:50)
at Error.ember$data$lib$adapters$errors$$InvalidError (http://localhost:4200/assets/vendor.js:69637:52)
at ajaxError (http://localhost:4200/assets/frontend.js:16:24)
at ember$data$lib$system$adapter$$default.extend.ajax.Ember.RSVP.Promise.hash.error (http://localhost:4200/assets/vendor.js:71327:31)
at jQuery.Callbacks.fire (http://localhost:4200/assets/vendor.js:3350:30)
at Object.jQuery.Callbacks.self.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3462:7)
at done (http://localhost:4200/assets/vendor.js:9518:14)
at XMLHttpRequest.jQuery.ajaxTransport.options.send.callback (http://localhost:4200/assets/vendor.js:9920:8)

The response from the backend has a 422 Unprocessable Entity header, and the content is:

{
     "message":"Couldn't save client",
     "errors":{
          "name":["The name field is required."],
          "email":["The email field is required."]
      },
     "status_code":422
}

Tried (and Failed) Solutions

  • Ember data Rest adapter error handling not working
    Extending the RESTAdapter to override the ajaxError function, mine currently looks like this:

    ajaxError: function(jqXHR) {
    var error = this._super(jqXHR);
    if (jqXHR && jqXHR.status === 422) {
        var jsonErrors = Ember.$.parseJSON(jqXHR.responseText).errors;
        return new DS.InvalidError(jsonErrors);
    } else {
        return error;
    }
    }
    
    
  • Adding a catch statement to the save method, my save action is currently:

     save() {
        var self = this;
    
        function transitionToPost(post) {
            self.transitionToRoute('clients.show', post);
        }
    
        function failure(reason) {
            // handle the error
            console.log(reason);
            return false;
        }
    
        this.get('model').save().then(transitionToPost, failure).catch(failure);
    }
    
    
  • Testing out the ActiveModelAdapter - not sure what I was expecting to acheive with this one, but I got desperate; the result was still the same.

  • Ember Docs (http://ift.tt/1Vrk4oN)
    As you can see in my controller code above, I actually used this as a base

Please can you have a look and advise? Thanks in advance for any help!




observers do not fire when I set computed.reads() value to null

I have the following

_selection: computed.reads('selection'),

_selectionUpdated: Ember.observer('_selection', function() {
    //Do something
})

When I do the following, _selectionUpdated is called correctly

this.set('_selection', someObject);

However, when I do

this.set('_selection', null);

_selectionUpdated does not fire, any ideas why?




ember-simple-auth: Persisting session in localstorage using custom authenticator

Setup:

  • Ember : 2.0.2
  • Ember Data : 2.0.1
  • jQuery : 1.11.3
  • Ember Simple Auth : 1.0.0 (jjAbrams Branch)
  • Ember CLI : 1.13.8

I'm using pretender to mock a server.

Usecase:

Using a custom authenticator to interface with the server.

Have 2 routes: login, protected (and by default index,application)

When I login with the right credentials, the authenticate method of the authenticator gets called and successfully logs the response object which is passed to resolve().

Observations:

  1. After logging in and being directed to the protected page, Refreshing the protected route (Which has AuthenticatedRouteMixin) leads back to login page.

  2. Localstorage has no values bound to it even after successful login. Before login: ember_simple_auth:session -> {"authenticated":{}}

  3. restore() method of authenticator never called.

  4. Going to another route from the protected route after auth and coming back goest to login page again.

//authenticators/custom.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';


export default Base.extend({
  restore: function (data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      console.log("RESOLVE",data);
      if (!Ember.isEmpty(data.token)) {
        //TODO Remove log

        resolve(data);
      } else {
        console.log("REJECTING",data);
        reject();
      }
    });
  },
  authenticate(credentials) {
    
    return new Ember.RSVP.Promise((resolve, reject) =>
      Ember.$.ajax({
        url: '/token',
        type: 'POST',
        data: JSON.stringify({
          email: credentials.identification,
          password: credentials.password
        }),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json'
      }).then(function (response) {
        Ember.run(function () {
          //This logs the expected information
          console.log("Response", response, response.token, response.user);
          resolve(response);
        });
      }, function (xhr, status, error) {
        console.log("error", error, xhr.responseText);
        var response = xhr.responseText;
        Ember.run(function () {
          reject(response);
        });
      }));
  },

  invalidate(token) {
    return API.logout(token);
  }
});
//environment.js
ENV['ember-simple-auth'] = {
  store: 'session-store:local-storage',
  routeAfterAuthentication: '/protected'
};

TLDR; How do I make the session persist?




ember build fails after code change

I am trying to run ember locally on my Windows 7 machine

When I load my app for the first time, the ember build is successful and ember serve starts and I can access my app.

However, as soon as I make even a small change in my code and try to refresh, I get the following error;

ENOTEMPTY, directory not empty 'C:\MyCode\myProj\tmp\tree_merger-tmp_dest_dir-cQOjj10S.tmp\modules\ember-validations\validators'

I am using Sublime Text editor and have added the following in Preferences: Settings > User

"folder_exclude_patterns": [".svn", ".git", ".hg", "CVS", "tmp/*"]

While I have seen other solutions like Disable Windows Search Index for temporary files (Windows does not seem to be already indexing my tmp folder) Disable Windows Defender for temporary files

Please note I do not have Admin rights on my system (it's a company provided system). I do have anti-virus running, but cannot disable it. So kindly suggest any fixes accordingly.




In Ember, is there a way to update a component without a full re-render/route transition

I have a map application. When clicking on a pin, I want to update a "teaser" component in the template by supplying e.g. a query parameter previewId without triggering a full re-render of the route, because that would re-initialize the map and center it on the init position, take a lot of time, in short: is ugly and bad user experience.

So what I have is a map route:

export default Ember.Route.extend({
    model: function () {    
        return this.store.findAll('map-object-proxy');
    }
});

a map controller, where I handle the query params:

export default Ember.Controller.extend({
    queryParams: ['previewId'],
    previewId: null,

    previewObject: Ember.computed('previewId', function () {
        return this.store.findRecord('map-object', 1);
    })
});

and a map-panel component which gets handed the previewObject from the map.hbs template:

<div id="map"></div>

<!-- ... -->

<div class="row" id="teaser-header">
    <div class="col-xs-12">{{previewObject.someProperty}}</div>
</div>

map.hbs has this Handlebars markup:

{{map-panel elementId="map-panel" objectProxies=model previewObject=previewObject}}

Sorry, I've not yet quite come to terms with ember's component architecture, even more so as controllers will be deprecated soon and somehow seem to act like a fifth wheel.

Thanks!




Creating ember addon for integration tests - can't get file into tests

(apologies for the title!)

I am trying to turn this:

http://ift.tt/1P54XSf

into an ember-cli-addon

I have read http://ift.tt/1RfoOgU which is great but I am stuck figuring out how to make the qunit-assert-html.min.js available in my tests.

All I have done so far is add the file to /vendor and then imported it inside index.js:

http://ift.tt/1P54XSh

npm linking the add-on into my project successfully adds the /vendor/qunit-assert-html.min.js to my apps /vendor folder but I can't figure out how to make that available in my integration tests.

Any help appreciated!




How to use a form component to submit to an external URL?

I have a form-tag component. It needs to submit to an outside url. I'm trying to do something like (pseudo code):

{{#form-tag action="http://ift.tt/1RfoQp5"}}
  {{input type="hidden" value=hiddenValue}}
{{/form}}

When the form submits, I need to end up at http://ift.tt/1RfoQp5

I'm tempted to use a <form> element instead. But was wondering if there was a way using a form component.




mardi 29 septembre 2015

Adding Ember CLI in a project that already exists

i want use Ember CLI, but i already have my own structure, i have all my backend ready for receive the client, and i can't change now, i'm working for months in this project.

I'm not finding a easy way to add the Ember CLI in my project, and i'm not finding any tutorial to help me achieve my needs.

My structure is like this:

| - bin
| - core
  | - client
    | - app
      | - site
        | - app.js                      // HERE I'M TRYING TO START THE EMBER
    | - public // Static files
    | - views
      | - site.layout.html
  | - server
    | - // All server files, not really matters here.
| - ember-cli-build.js
| - bower.json
| - package.json

I copy and past the informations and dependencies from the ember-cli boiler plate, so in my package.json i had just my server dependencies, and now:

"broccoli-asset-rev": "^2.1.2",
"ember-cli": "1.13.8",
"ember-cli-app-version": "0.5.0",
"ember-cli-babel": "^5.1.3",
"ember-cli-content-security-policy": "0.4.0",
"ember-cli-dependency-checker": "^1.0.1",
"ember-cli-htmlbars": "0.7.9",
"ember-cli-htmlbars-inline-precompile": "^0.2.0",
"ember-cli-ic-ajax": "0.2.1",
"ember-cli-inject-live-reload": "^1.3.1",
"ember-cli-qunit": "^1.0.0",
"ember-cli-release": "0.2.3",
"ember-cli-sri": "^1.0.3",
"ember-cli-uglify": "^1.2.0",
"ember-data": "1.13.8",
"ember-disable-proxy-controllers": "^1.0.0",
"ember-export-application-global": "^1.0.3",

In the bower.json i have:

"ember": "1.13.7",
"ember-cli-shims": "ember-cli/ember-cli-shims#0.0.3",
"ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
"ember-data": "1.13.8",
"ember-load-initializers": "ember-cli/ember-load-initializers#0.1.5",
"ember-qunit": "0.4.9",
"ember-qunit-notifications": "0.0.7",
"ember-resolver": "~0.1.18",
"jquery": "^1.11.3",
"loader.js": "ember-cli/loader.js#3.2.1",
"qunit": "~1.18.0"

I already made npm install and bower install, so i have all dependencies installed.

In the ember-cli-build.js i have:

/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};

As you can see, i just copy and past the code and dependencies from Ember-CLI.

This is not enough to make Ember CLI works??

In the app.js (see the tree) i have:

import Ember from 'ember'

But is giving me this error:

Uncaught SyntaxError: Unexpected reserved word

What i'm doing wrong here??




Ember with ajax post creates an additional browser history before the actual page, thus, you needing to click back button twice

Our client calls our webpage built in ember. Our webpage initiates an ajax post to the back-end using restful web-service to authenticate the session id before showing the pages. I noticed that the browser history creates two entries, one created from the ajax call (URL with session) and the actual page (URL with session plus hashed name automatically done by ember defined in your router) respectively.

Now, our Ember page has a BACK button that just implements the history.go(-1). Because the loading of the page generates two history entries, i need to press it twice.

My initial thought was to use history.go(-2) but i want a better fix of having to make history.go(-1) work. Let's say, making the ajax call not create an additional entry in the history.




Uncaught TypeError ember serve Windows

I am using ember-cli 1.13.8 and I just generated some pretty simple mocks and now my app won't start with ember serve or ember server

getting this error in the console Unexpected identifier SyntaxError: Unexpected identifier at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:413:25) at Object.Module._extensions..js (module.js:448:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Module.require (module.js:365:17) at require (module.js:384:17) at Array.map (native) at module.exports (C:\app\server\index.js:13:68) at Class.module.exports.Task.extend.processAppMiddlewares (C:\app\node_modules\ember-cli\lib\tasks\server\express-server.js:107:14)

my index.js file for the server looks like this

module.exports = function(app) {
  var globSync   = require('glob').sync;
  var bodyParser = require('body-parser');
  var mocks      = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
  var proxies    = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);

  // Log proxy requests
  var morgan  = require('morgan');
  app.use(morgan('dev'));
  app.use(bodyParser.json());

  mocks.forEach(function(route) { route(app); });
  proxies.forEach(function(route) { route(app); });
};




this.store.find is not a function

i would like to get all my events from the API ROUTE /events (GET) in my IndexRoute, so i'm trying like this:

SiteApp.IndexRoute = Ember.Route.extend({
 model: function() {
  return this.store.find('events');
 }
});

And is returning the error:

this.store.find is not a function

I'm not understand why this.

I'm loading the libs in this sequence:

jQuery
Ember Data
Ember Template Compiler
Ember Debug

Thanks.




Which drag and drop to use? jQuery draggable droppable or EmberJS native drag-and-drop?

We are developing a drag and drop CMS called ucraft.me. It is based on Laravel + EmberJS + jQuery + Greensock(GSAP).

Imagine it works the following way:

  1. There is a blank page with a left panel, where you have different modules to craft your pages. Ex., title, button, image, slider, video, etc...
  2. The white page is based on a grid where there can be max 4 modules.

Now imagine we have a module - button, in the centre of a full width row(span12) and now we decided to drop another module, like Title, which will split the current row into span6 - span6. Currently we are using jQuery draggable droppable, to calculate all the droppable areas and to let the user drop certain elements.

Can someone recommend a better drag and drop library to implement this, is there anyone with a similar experience? Do you think jQuery draggable-droppable is a good choice to implement the drag and drop feature in the site builder? Does it have good performance?

Or should we use EmberJS native drag-and-drop library?

Thanks!!




Convert Ember Model Attribut to String

I have a template where I am trying to set the input value of an html form to a model.name value. However, I don't want changes in this box to affect the global store. Can I convert model.name to be string only?




Ember action : target only 'this' of #each

I have a few actions that I'm placing on each item in a loop. Currently the action reveals all of the book-covers, instead of just one I want to target.

http://ift.tt/1VlSuPg

Looks like I can pass a parameter, but I'm not sure of the syntax.

I've done this before in earlier version and remember using this or should it be

{{action 'showCover' book}} ... ?


Controller

import Ember from 'ember';

export default Ember.Controller.extend( {

  actions: {
    showCover() {
      this.set('coverVisible', true);
    },
    ...
  }

});


Template

{{#each model as |book|}}

    <li class='book'>
        <article>
            {{#if coverVisible}}
            <figure class='image-w book-cover'>
                <img src='{{book.cover}}' alt='Cover for {{book.title}}'>
            </figure>
            {{/if}}

            ...

            {{#if book.cover}}
            {{#unless coverVisible}}
            <div {{action 'showCover'}} class='switch show-cover'>
                <span>Show cover</span>
            </div>
            {{/unless}}
            {{/if}}

{{/each}}




Will that be possible to render Joomla's frontend in EmberJS/AngularJS

I am an old Joomla user and know this system quite well. But it is still a little bit slow to perform maybe because of different css/js includes by 3rd party components, etc.

My question is: Is there a way to integrate Joomla's frontend with EmberJS/AngularJS, use Ember's routing, get all the data in JSON and have a faster frontend. In this way we can ignore Joomla's on every page load, which will cut down my page's load time!

Do you think this is a good idea? There are a lot of articles where people are sharing their experience with EmberJS + Laravel or AngularJS + Laravel, for example. Joomla can stand for Laravel as a backend and provide EmberJS/AngularJS with the necessary info to render the correct page.

This way we can have the greatest CMS Joomla as a Single Page Application on the frontend.

Please let me know your ideas on this! Thank you!




How do you render a template dynamically when not leaving a route?

I'm working on a tabbed modal, whose endpoint looks like 'account/tab_id'. When navigating from, say 'account/1' to 'account/2' the url updates as it should and all of the hooks kick off as intended with the exception of the renderTemplate hook. Do you have any thoughts on how I can rework this to get that hook firing? My relevant route code looks like:

model:function(params){
    var tabId = params.tab_id, 
    parentModel = this.modelFor('dashboard.home.account');
    this.set('tabId',parseInt(tabId));
    return parentModel;
},
afterModel:function(model){
    this.set('modelName',model.get('_internalModel.modelName'));
    this.set('templateName',this.get('modelName') + '/' + this.get('tabId'));
},
renderTemplate: function(controller,model) {
    //not getting called after first render
    this.render('edit.'+ this.get('templateName'),{ 
        into:'dashboard',
        outlet: 'modal' 
    });
},




Can HTMLbars be used without Ember.js?

I've been looking for a while now, and every time HTMLbars is mentioned Ember is involved. The problem is I want to migrate from Handlebars to HTMLbars, however my project has a custom framework. If all that HTMLbars does it make it so the content is returned as HTML elements, rather than a string, why is it Ember exclusive, and has anyone found a way to work around that exclusivity.




Ember Rerender ClassNameBindings Failing

I have a component which needs to be re-rendered based on a controller variable change. However, everytime I rerender my component, I loose the classNameBindings. How can I avoid this?

Component

import Ember from 'ember';
export default Ember.Component.extend({
    isShown: false,
    classNameBindings: ['isShown::hide'],
    reloadComponent: Ember.observer('isShown', function () {
        this.rerender();
    }),
});

Template that renders the component.

{{my-component isShown=isShown}}

Controller for the route

export default Ember.Controller.extend({
    isShown: false,
});

Some function changes the value of isShown. That gets changes in component. However, the classNameBindings in component are lost. They always show 'hide class' irrespective of isShown variable value.

Why does this happen? How can I avoid this?




How to install ember-collection using ember-cli?

I'm trying to install ember-collection on my ember-cli application...

using ember install ember-collection I get:

version: 1.13.8
Installed packages for tooling via npm.
Install failed. Could not find addon with name: ember-collection

If I install it from bower, the component directory has just an empty file inside...

If I install it from bower specifying the repository, I get the files in my bower folder but I can't find a way to import it in my project.

I have created an ember-collection.js component with inside:

import EmberCollection from 'ember-collection/components/ember-collection';
export default EmberCollection;

But then I get:

Uncaught Error: Could not find module `ember-collection/components/ember-collection` imported from `myapp/components/ember-collection`

How can I do?




Index model not updating after saving nested model

I'm not sure if maybe I'm doing this wrong in ember, or if I have my structure wrong, or if there is something else I need to implement here, but after editing a nested model from the parent index model it's not updating to reflect the changes in the parent route.

My routes are set up as so

this.route('followers', function() {
  this.route('new');
  this.route('edit', { path: 'edit/:follower_id'});
});

I have a templates/followers/index.hbs

{{#each model as |follower|}}
    ...
{{/each}}

And then I have a link in each model that links to the edit route

{{#link-to "followers.edit" follower.id}}<span class="glyphicon glyphicon-cog edit-action" aria-hidden="true"></span>{{/link-to}}

And in my templates/followers/edit I have a form

<form {{action "editFollower" on="submit"}}>
  <div class="form-group">
    <label for="username">Username</label>
    {{input value=model.username name="username" class="form-control" placeholder="Username"}}
  </div>
  <div class="form-group">
    <label for="minutes">Minutes</label>
    {{input value=model.minutes name="minutes" class="form-control" placeholder="Minutes"}}
  </div>
  <div class="form-group">
    <label for="currency">Currency</label>
    {{input value=model.currency name="currency" class="form-control" placeholder="Currency"}}
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

This calls an action on my controller controllers/followers/edit

editFollower: function(defer) {
    var self = this;
  var follower = self.get('model');
  follower.save().then(function(){
    self.get('notify').success('Follower edited');
    self.transitionToRoute('followers.index');
  }).catch(function(){
    alert('there was a problem');
  });
}

This all works up to this point however after transitioning back to the index route I have to refresh and hit the API again to see the changes that the edit action made. Is this not possible with my current pattern or did I just set it up wrong?




How do I get cookies to to be sent with my requests to the backend in ember app

Is there a way in ember to send cookies with the requests to the backend?

For example: if my client url is protocol://example.com . The cookies that belong to the same domain will be in the request header when I navigate to protocol://example.com/profile. However, they do not persist in the subsequent request/s the profile route model method makes -> example to protocol://example-host/posts . How do I make those cookies persist?

/app/routes/profile.js

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

export default Ember.Route.extend({
  model: function () {
    return this.store.findAll("post");
  },
  setupController: function (controller, model) {
    // setup controller
  },

  renderTemplate: function () {
    this.render("header", {
      outlet: "header"
    });

    this.render("profile");
  }
});

/app/adapters/application

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

export default DS.RESTAdapter.extend({
  host: http://example-host.com,
  corsWithCredentials: true,
  crossDomain: true,
  xhrFields: {withCredentials: true},
});




Ember ember-views.render-double-modify

Using Ember.2.1.0-beta4

I am getting the "ember-views.render-double-modify" in a function triggered by the "didReceiveAttrs" of a subcomponent.

I tracked down the statement this.set('_columns', columns) that triggers the error. However, AFAIK this is the first time the attribute is modified.

To debug it, I created an observer for the modified attribute, and put a breakpoint there. However, the observer is only called once and the error is still there, so it looks like this is the first call.

How should I debug this -- is this an Ember bug, or are there other restrictions on setting attributes that aren't clear in the error? Note that the attribute is used in the component's template. Also the attribute is used in other computed attributes (e.g. _columns.@each.width and _columns.[]).




Delete Record in Emberjs

I am struggling to follow ember 2.0's documentation for deleting records and then redirecting to a new url. When I try, I get the following error to the console:

TypeError: Cannot read property 'get' of undefined

My files follow.

Routes:

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

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

Router.map(function() {
    this.resource('pencilview', { path: '/pencils/:pencil_id' });
    this.resource('pencilcreate', { path: '/pencils/new' });
    this.resource('pencils');
});


export default Router;
import Ember from 'ember';
import config from './config/environment';

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

Router.map(function() {
    this.resource('pencilview', { path: '/pencils/:pencil_id' });
    this.resource('pencilcreate', { path: '/pencils/new' });
    this.resource('pencils');
});


export default Router;

routes/pencilview.js

export default Ember.Route.extend({
    model: function(params) {
      return this.store.find('pencil', params.pencil_id);
    },

    actions: {
        save(pencil){
            this.store.find('pencil', pencil.id).then(function(pencil){
                pencil.save();
            })
            this.transitionTo('pencils');
        },

        remove(id){
            this.get('store').find('pencil', id).then(function(pencil2){
                pencil2.deleteRecord();
            });
            this.transitionTo('pencils').then(function(id){
                this.get('store').find('pencil', id).then(function(pencil2){
                    pencil2.save();
                });
            });
        },

      cancel(pencil){
          this.store.find('pencil'.pencil.id).then(function(pencil){
          })
      }
  }
});

templates/pencilview.hbs

<h2>Single Pencil View</h2>
<p>Pencil ID: {{model.id}}</p>

<p>
<label for='name'>Name</label>
{{input type="text" id="name" value=model.name}}</p>

<p>
<label for='tradeName'>Trade Name</label>
{{input type="text" id="tradename" value=model.tradeName}}</p>

<p>
<label for='bbb'>Blood Brain Barrier</label>
{{input type="text" id="bbb" value=model.bloodBrainBarrier}}</p>

<p><button {{action "remove" model.id}}>Delete</button></p>
<p><button {{action "save" model}}>Save</button></p>

{{#link-to 'pencils'}}Pencils{{/link-to}}




Render ember page on server using Django

I have a Django application that has two parts: 1- Rest API using Django Rest Framework 2- Index.html - This is Ember app that calls the Rest API.

Both apps are hosted on Django server, and all is fine. Now I need a way to render Index.html page, which contains a lot of Ember.js code on the server using Django template render, or render_to_string and store the output as a static html that can be used later as a body of an email message, or just previewed on a browser.

So far, the template render, doesn't work! Do you have a better suggestion on how to do this? Note: I also want to pass additional route parameters to the server render like http:127.0.0.1:8001/#/books/1 ... http:127.0.0.1:8001/#/books/55 ... So each one of these will be stored as its own html.




Emberjs: In my template I can't get a value from a form my controller

I create a template and it's controller and i set a variable(value) in controller but when i try to access in template noting to happen. my controller is:

    App.AboutController = Ember.Controller.extend({
    info:null,
    init: function() {
        console.log("yes i am in About controller");
        info = post["about"];
    },
  actions: {
    getdata1:function(data){
    console.log("aa gaya",data);
    info = post[data];
    console.log(info);
    }

  }

and Template is:

<script type="text/x-handlebars" id="about" data-template-name="about">
<div class="col-xs-6 middlesubBody">
               {{info}}
           </div>
            <div class="col-xs-3 rightsubBody">
                <div id="column">
                        <div
                        {{action "getdata1" "about"}}> About</div>
                        <div>
</div>
</script>

MY Action is working fine but info value is not set to template.i want to dynamic binding . I think i am wrong but i don't know where is problem.




How to bubble up a rejected promise when using Ember.PromiseProxyMixin

I am using Ember's PromiseProxyMixin with AJAX data calls and Ember RSVP Promises. Rather than incorporating error-handling in each route/template, I would like to bubble a rejected promise up to an error handler in the Application route as follows:

export default Ember.Route.extend({
    actions: {
        error: function(error, transition) {
            return this.transitionTo('error');
            return false;
        }
    }
});

Currently, if a promise is rejected, the rejected promise doesn't appear bubble up to the Application route (is this because the PromiseProxyMixin attaches to a promise's .fail() function and prevents further bubbling? If so, is there any way of continuing the bubbling?)

Is it possible to use the PromiseProxyMixin and also allow the rejected promise to bubble up to the Application route?

Thanks for your help.




No persistent data on Firefox OS using ember-localforage-adapter

I've got an issue with using this adapter. I'm a noob in Ember, so it might be (and probably is) my error...

Ember 1.13.8 Ember Localforage Adapter 1.13.1

  • Adding an entry is fine - adapter is called.
  • Adapter isn't called when the application is started.
  • Data is missing when an app is reloaded.

http://ift.tt/1FF5urM




How to use Ember in visual studio 2012

I need to create a spa using ember js in visual studio 2012.I tried with installing 'EmberJS SPA Template Project' via http://ift.tt/1gzKNgW but on creating new project it doesnt show me option for SPA.Thanks in advance!!!




Ember Simple Auth ENOENT Error

I am new to ember , now building an application which uses the simple-auth ember combination. But i am getting error while starting the ember app.

Error: ENOENT, no such file or directory '/var/www/test-cli/frontend/tmp/concat_with_maps-input_base_path-http://ift.tt/1KHq5eb'
at Error (native)
at Object.fs.statSync (fs.js:797:18)
at ConcatWithMaps.keyForFile (/var/www/test-cli/frontend/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/index.js:91:55)
at Array.map (native)
at ConcatWithMaps.CachingWriter._conditionalBuild (/var/www/test-cli/frontend/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/index.js:107:61)
at /var/www/test-cli/frontend/node_modules/ember-cli/node_modules/broccoli-sourcemap-concat/node_modules/broccoli-caching-writer/node_modules/broccoli-plugin/read_compat.js:61:34
at lib$rsvp$$internal$$tryCatch (/var/www/test-cli/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:493:16)
at lib$rsvp$$internal$$invokeCallback (/var/www/test-cli/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:505:17)
at lib$rsvp$$internal$$publish (/var/www/test-cli/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:476:11)
at lib$rsvp$asap$$flush (/var/www/test-cli/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1198:9)

Saying that some files are missing . Looks like this bug is with the new version of those devise dependancies . Also reported here http://ift.tt/1iYagHh. It would be great if some one could share a solution to fix it. Thanks




lundi 28 septembre 2015

Need to initiate the multiple jquery dialog

Here, I have a jquery dialog using an ember component. I want to have a multiple dialog.

In my js:

App.IndexRoute = Ember.Route.extend({

  actions: {
    test: function () {
      var self = this;
      self.get('controller').set('isConfirmDialog', true);  // No I18N
      self.get('controller').set('dialogContent', "Hi, Alert!");  // No I18N
    }
  }
});

App.IndexController = Ember.Controller.extend({
    isConfirmDialog: false,
    dialogContent: ''
});
App.ConfirmDialogComponent = Ember.Component.extend({

    defaultOptions: { 
        height:'300', // No I18N
        width: '300', // No I18N
        modal: true, // No I18N
        title: 'Alert', // No I18N
    },
    didInsertElement: function(){
        var self = this; // No I18N
        self.send("showConfirmDialog"); // No I18N
    $("#dialogdiv").bind('dialogclose', function(){ // No I18N
        $("#dialogdiv").html('').dialog('destroy'); // No I18N
        self.sendAction('dialogreset'); // No I18N
    });
},
actions: {

    showConfirmDialog: function(){
        var self = this; 
        self.set('defaultOptions', $.extend( {}, self.get('defaultOptions'), self.get('dialogObj') )); // No I18N

        $( "#dialogdiv" ).dialog( self.get('defaultOptions') ); // No I18N
    }
}

});

In my Template:

<script type="text/x-handlebars" data-template-name="index">
   <button {{action "test"}}>Alert</button>
   {{#if controller.isConfirmDialog }}   
       {{confirm-dialog dialogContent=dialogContent dialogreset='resetDialog'}}  
   {{/if}}   
</script> 

 <script type="text/x-handlebars" data-template-name="components/confirm-dialog">
     <div id="dialogdiv">{{{controller.dialogContent}}}</div>
 </script>

This is how I am initializing my dialog component. If I need to initiate the other dialog inside that dialog while click the content "Hi, Alert!", what should I do? Let me know if I missing any logic or anything.

My working link : JSBIN




Ember 2.0 upgrade errors: Unexpected strict mode reserved word & handlebars precompile error

I'm trying to upgrade an ember-rails app from ember v1.13 to v2.0. The app loads and templates render in ember 1.13 and there are no deprecations coming through to the console. When I bump the version to 2.0.0 (through the ember-source gem), the app doesn't seem to load and no templates are rendered. Instead, this error is in the JS console: Uncaught Error: ExecJS::RuntimeError: SyntaxError: Unexpected strict mode reserved word If I refresh the page, suddenly I'm hit with a handlebars precompile error:

Uncaught Error: Barber::PrecompilerError: Pre compilation failed for: (prints out file contents) Compiler said: ReferenceError: Handlebars is not defined

Any thoughts on what could be the cause of this? Any input would be greatly appreciated, as I've been stuck on this for hours!!!




How do I control ember component observer execution order?

I have a component within a component. The child component has two properties passed-in via the template. These properties both have separate observers within the child's component.js.

When I update the bound properties in the parent component in a specific order, the child component's observers fire in the wrong order.

How can I control the order in which the observers fire in the child component?




Embli-Cli Not work after Building

Iam working around Ember-Cli.I build a project and customize the "ember-cli-build.js" but finally it doesn't work. this is my work steps:
1) ember new myapp cd myapp ember server it works fine and i can see my project on "http://localhost:4200"
2) then run ember build --environment=production and get Built project successfully. Stored in "dist/". so it appear that my project built.
3) then i run this url on browser that direct to my dist directory project

localhost/~/myapp/dist/index.html

but nothing shows. i check the console and it seems that the "ember" is running, but nothing shows on the screen




How to overwrite or alter data in child ember component

I have two simple ember components; a list component and a list-item component. Data gets passed as an array to the list where it runs an each loop and makes a list-item component for each item in the array.

I'd like to, within the list-item component, take the data being passed to it from its parent list component and overwrite it. Eventually I would like to do more than just overwrite it and use it as a parameter in a function to return a new, parsed, value.

For the sake of example, lets say that this is a list of tweets.

Here is my code.

ROUTER.JS

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

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

Router.map(function() {
  this.route('tweets');
});

export default Router;

TEMPLATES/TWEETS.HBS

{{tweet-list tweets=model}}

ROUTES/TWEETS.JS

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return[{
      tweetText: "this is an example  #request tweet text1 @user"
      },{
      tweetText: "tweet of the @text2 how #cool"
      }, {
      tweetText: "tweet toot took text3"
    }];
  }
});

COMPONENTS/TWEET-LIST/COMPONENT.JS

import Ember from 'ember';

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

COMPONENTS/TWEET-LIST/TEMPLATE.HBS

<ul>
  {{#each tweets as |tweet|}}
    <li>{{tweet-item tweet=tweet}}</li>
  {{/each}}
</ul>

COMPONENTS/TWEET-ITEM/COMPONENT.JS

import Ember from 'ember';

export default Ember.Component.extend({
// model(){
// return "over written value here"
// }
});

COMPONENTS/TWEET-ITEM/TEMPLATE.HBS

{{tweet.tweetText}} - <!-- {{overwritten value here}} -->

I believe I have to do the overwriting in the COMPONENTS/TWEET-ITEM/COMPONENT.JS file ? How do I go about overwriting or, even better, returning a new value based off of the data passed down from the parent component?




JSON API response and ember model names

A quick question about the JSON API response key "type" matching up with an Ember model name.

If I have a model, say "models/photo.js" and I have a route like "/photos", my JSON API response looks like this

{
  data: [{
    id: "298486374",
    type: "photos",
    attributes: {
      name: "photo_name_1.png",
      description: "A photo!"
    }
  },{
    id: "298434523",
    type: "photos",
    attributes: {
      name: "photo_name_2.png",
      description: "Another photo!"
    }
  }]
}

I'm under the assumption that my model name should be singular but this error pops up

Assertion Failed: You tried to push data with a type 'photos' but no model could be found with that name

This is, of course, because my model is named "photo"

Now in the JSON API spec there is a note that reads "This spec is agnostic about inflection rules, so the value of type can be either plural or singular. However, the same value should be used consistently throughout an implementation."

So,

tl;dr Is the "Ember way" of doing things to have both the model names and the JSON API response key "type" both be singular? or does it not matter as long as they match?




How to prevent Ember Data from saving attribute (ie., Read-only attribute)

I am creating an online form builder using Ember 2.0 on the front-end and Rails 4.2 on the back-end with the json_api_resources gem.

In the process of publishing a form, a user must be able to cut/paste a snippet of code into his/her webpage in order to 'ajax in' the form they have configured.

Thus the 'embed-snippet' attribute of the Form model should be read-only. I do not want the contents of the snippet field to be sent back to the server when the user makes a change to the form and re-saves the record.

Some approaches I have considered:

  • Modifying the serializer to check for this specific attribute and drop it from the payload before sending it to the back-end
  • Converting the 'embed-snippet' field to a separate model with a relationship to the Form model, and then excluding it somehow from the save
  • Creating a new Ember Data attribute type

Ideally there would be a better way to deal with this problem.

Something like:

'DS.attr('string', { readOnly: true })

So my question is, what is the best way to ensure this field does not get sent back to the server?




How to pass computed properties from route to component

Taking the following as an example:

  <script type="text/x-handlebars">
    <h2>Welcome to Ember.js</h2>

    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="index">
    <ul>
    {{#each model as |item|}}
      <li>{{item}}</li>
    {{/each}}
    {{magnus-component name=firstName}}
    </ul>
  </script>

  <script type="text/x-handlebars" data-template-name="components/magnus-component">
  <!-- Doesn't appear -->
    {{name}}
  </script>

...and

App = Ember.Application.create();

App.Router.map(function() {
});
App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue'];
  },
  name: "Magnus",
  surname: "Womble",
  fullName: Ember.computed('name', 'surname', function(){
    return this.get('name') + ' '+this.get('surname');
  })
});

Which can be found in the following jsbin:

http://ift.tt/1RbZ2tR

How do you correctly pass the fullName property to the component template?




Ember Data Not Using Irregular Model Name

In my project, I have a inflector setup for a model with an irregular name, campus For some reason, after updating from Ember CLI 0.2.7 to Ember CLI 1.13.8, the inflector is no longer being applied to the model.

When trying to access the store, this.store.findRecord('campus', params['campus_id']), I get a warning

WARNING: Encountered "campus" in payload, but no model was found for model name "campu" (resolved model name using app@serializer:campus:.modelNameFromPayloadKey("campus"))

followed by this error

No model was found for 'campu' Error: No model was found for 'campu'

The return payload looks something like this

{
  campus: {
    id: 1,
    name: "Default Campus"
  },
  meta: {
    total: 1,
    page: 1
  }
}

and I have been using an initializer with previous success

import Ember from 'ember';

export function initialize(/* registry, application */) {
  var inflector = Ember.Inflector.inflector;
  inflector.irregular('campus', 'campuses');
}

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

I've tried updating to the most recent version of Ember Data, 1.13.13, and updating the ember inflector to 1.9.3. I've also tried to move the irregular inflector into the model but am no closer to resolving the issue

I've also tried running the following code in the console before making a call to the store to see what the inflector is set to

var inflector = Ember.Inflector.inflector;
inflector.singularize('campus') // returns "campus"
inflector.pluralize('campus') // returns "campuses"

This issue is extremely frustrating since there doesn't seem to be anyway to resolve it.




What are the respective purposes of the emberjs.com and ember-cli websites?

I am a bit confused regarding the ember websites "emberjs.com" and "ember-cli.com". Isn't ember-cli now a part of emberjs and documented at "emberjs.com"? If so, why have a different website for ember-cli? Also, why do the sites differ regarding the versions of the prerequisite JS frameworks? For example, the emberjs.com getting starting page says to use Node.js 0.12 or higher while the ember-cli.com site says to use the latest stable version of Node (version 4.0.x).




emberjs find then filter

In emberjs, considering the following data (only showing 1 record, normally there would be multiple records):

{ "service": [{
    "service-_id":"service_5606ece79bdb05546479739866",
    "service-_rev":"5-62dc477c13ef3ea92869bcdf1a67f1a6",
    "service-company-name":"ABC co.",
    "service-address":"1 2 3 Main Street",
    "service-address-line-2":"",
    "service-city":"asfd",
    "service-state-current":"NY",
    "service-zip":"12345",
    "service-phone":"111",
    "service-fax":"",
    "service-email":"asdf@adsf.com",
    "service-category-current":"web",
    "service-type":"service",
    "id":"service_5606ece79bdb05546479739866"
}]}

If I want to return all the records, I can simply do this:

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

However, let's say I want to return all the records that have the current category as 'web'. So in the example data, there is this key: service-category-current

How would I adjust my model to find 'service' then filter where service-category-current = 'web' ?




Ember.js: Internal hyperlinks when pulling from a database

My database sometimes contains hyperlinks (regular HTML "a" tags) to other routes within my Ember.js application. The issue is that I do not know how to have it so those links will be transitioned within Ember instead of having to reload the page. Is there any way to get around this issue?

Example: I have product (/products/name) content being pulled from my Rails backend. This content contains a link to contacts (/contact). Clicking on that link will force an app reload instead of doing an Ember transition. Is there a way to force the link to be handled within Ember?




How to extend addon in Ember 1.13.8 in component?

I am using the ember-cli-mandrill addon, and I am attempting to connect a contact form to mandrill, I keep getting the error:

Uncaught TypeError: Cannot read property 'send' of undefined

I am guessing I am not extending the addon correctly. If not, any ideas on what could be causing this error, I included the component in jsfiddle example.

http://ift.tt/1iWDPJc




Promise reject not returning?

I'm working with ember.js and have a problem with the simple auth token package not returning a rejected promise, and I'm not sure why.

The issue that I'm trying to solve is to show an error message if the authentication is rejected, for this example we can even just show a hard-coded message if it fails for any reason. The behavior that I'm seeing is that a couple errors show up in the console, but no message is shown.

POST http://localhost:8000/v1/auth/login/ 400 (BAD REQUEST)

undefined: _emberMetalLogger["default"].error(error.stack);

// my authenticate action
authenticate: function() {
   let store = this.container.lookup('store:main');
   let credentials = this.getProperties('identification', 'password'),
      authenticator = 'simple-auth-authenticator:token';
      let authPromise = this.get('session').authenticate(authenticator, credentials);

      authPromise.then(() => {
        console.log('inside authPromise');
        let userPromise = store.find('user', {username: credentials.identification});

        userPromise.then(user => {
            console.log("inside userPromise");
            store.find('store', {user: user.get('firstObject').get('id')}).then(function(store) {
                this.get('appController').set('myStore', store.get('firstObject'));
            });
        }, err => {
            console.log('in error block');
            this.set('errorMessage', 'Unable to login with the provided credentials');
        });
    });
}

My authenticate action fires, but it never can get into the error block, nor can it reach inside the authPromise. As soon as it defines the authPromise the error happens and everything stops. I've tried even putting a try/catch around it, but I can't get anything returned with that etiher. I would expect the promise to reject and use the second function with the following response.

Diving a little further into the guts, I wanted to make sure the promise was being rejected properyly. In the package the authenticate function is fired and it does reject the promise according to the console.log() that I put in while debugging. The 2 variables it uses in the reject are defined as well, so I'm not sure when I'm not getting the rejected promise returned.

// authenticate action in the ember-simple-auth-token package
authenticate: function(credentials) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var data = _this.getAuthenticateData(credentials);
      _this.makeRequest(data).then(function(response) {
        Ember.run(function() {
          resolve(_this.getResponseData(response));
        });
      }, function(xhr) {
        Ember.run(function() {
          console.log('rejecting');
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });
  },




Rails web socket - authorization

I have Ember.js client and RoR server side with gem "websocket-rails".

I need to get private channel with authorization to send messages only for one user.

This is how I try:

class AuthorizationController < WebsocketRails::BaseController

    before_action :require_login

    def authorize_channels
        # The channel name will be passed inside the message Hash
        puts '*'*400
        ap current_user//Here I see the user

        channel = WebsocketRails[message[:channel]]
        accept_channel current_user

    end


    def require_login

        sign_in(User.find(4))

    end
end

My events.rb is:

WebsocketRails::EventMap.describe do
    namespace :websocket_rails do
        subscribe :subscribe, :to => AuthorizationController, :with_method => :authorize_channels
    end

end

But when I try to send message with:

WebsocketRails.users[4].trigger(:test_event, { message: 'This is a private message from WebSocket Rails' } )

I get error "#>"

And if I try to print WebsocketRails.users I see:

#<WebsocketRails::UserManager:0x007ff5bb617d68 @users={}>

What is wrong? Thx a lot!




How do I initialize a child index route with a dynamic segment in Ember?

I'm trying to piece together an index route that initializes to the first item of a returned collection from the parent route. In this case we gather 'plans' for a specific user and would like to serialize the index route to their first plan id. So 'app/USER_ID' would route to 'app/USER_ID/FIRST_PLAN_ID'. In addition the index route that utilizes the plan id would have child routes that we want to hit directly via url.

  this.route('dashboard', {path: '/:client_id'}, function() {
       this.route('index', {path: '/:plan_id'}, function() {

This index route will have child routes. The problem with this approach is that the 'dashboard' route's hooks do not get hit once I add in the index route, and it's not included in the transition object that's passed to the children (it's as if it's replaced by the index route).

We first went the route of doing a manual transition from the dashboard route to a child route called 'home' instead of index. This initialized properly but the transition caused any nested route under 'home' to be inaccessible via URL due to the 'transitionTo' at the dashboard level. For example, attempting to navigate to 'app/USER_ID/PLAN_ID/ACCOUNT_ID' would resolve to 'app/USER_ID/PLAN_ID' because a hook in the parent route would essentially scrub the rest of the route. How would one properly initialize a route to a dynamic segment using a dynamic segment in the parent route without losing the ability to navigate to descendant routes?




Ember 2, ember-cli, render partial to only show categories title, but it doesn't work

I have normal, basic ember-cli project.

This is my application.hbs:

<div class="container-fluid">

    <div class="row">

    <div class="col-sm-3 col-md-2 sidebar">
      {{render 'sidebar'}}
    </div>

    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">

        {{outlet}}

      </div>

    </div>

</div>

This is my post.hbs:

{{#each model as |post|}}
    {{post.text}}
{{/each}}

This is my sidebar.hbs:

<ul class="nav nav-sidebar">
  {{#each model.posts as |post|}}
    <li>{{#link-to author}}{{post.author.name}}{{/link-to}}</li>
  {{/each}}
</ul>

and everything else is standard.

How to make work {{render 'sidebar'}} with just the title of my categories?

Now it shows nothing.




Loading a single record with Ember 2.0 and Ember Data 2.0

G'day all,

I've come unstuck when trying to fetch a single record using Ember Data 2.

The server is designed to respond to a GET request like this:

GET http://server/api/results/1

with this as a result:

{
   "results" : [
     {
        "id": 1,
        "catname": "Category 1",
     }
   ]
}

The Ember route code looks like this:

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

The problem is that there doesn't appear to be a network request going out (a previous findAll fetch has worked, so I don't think it's the adapter), and there is an error I have not been able to find informaiton on:

Uncaught TypeError: Cannot set property'crossDomain' of undefined

Does anyone have any idea what this could be, of hint at how I might track this down?

Thanks,

Andy




Ember-cli, Masonry, Isotope, Packery. How to use?

I need to use them in my ember-cli project.

How to start?

I writed in terminal:

bower install isotope --save

then in my ember-cli-build.js I added app.import ecc..., but then I don't know what to do.

Where to put my intialization script, like this:

$('.grid').isotope({
  // options
  itemSelector: '.grid-item',
  layoutMode: 'fitRows'
});

If I put it in application.hbs it give to me an error and when i change route with {{#link-to}} it doesn't work anymore.

What to do?

In the web there aren't many resources about this.




Error when trying to start ember server

I am trying to start my server from within my app using the command;

ember serve

However I get a no such file or directory error as below;

version: 1.13.8
Livereload server on http://localhost:49156
Serving on http://localhost:4200/
ENOENT, no such file or directory 'C:\MyApp\mycode\tmp\concat_with_maps-input_base_path-tfPGUnEW.tmp\0\bower_components\ember-template-compiler\index.js'
Error: ENOENT, no such file or directory 'C:\MyApp\mycode\tmp\concat_with_maps-input_base_path-tfPGUnEW.tmp\0\bower_components\ember-template-compiler\index.js'
    at Error (native)
    at Object.fs.statSync (fs.js:797:18)
    at ConcatWithMaps.keyForFile (C:\MyApp\mycode\node_modules\ember-cli\node_modules\broccoli-sourcemap-concat\node_modules\broccoli-caching-writer\index.js:91:55)
    at Array.map (native)
    at ConcatWithMaps.CachingWriter._conditionalBuild (C:\MyApp\mycode\node_modules\ember-cli\node_modules\broccoli-sourcemap-concat\node_modules\broccoli-caching-writer\index.js:107:61)
    at C:\MyApp\mycode\node_modules\ember-cli\node_modules\broccoli-sourcemap-concat\node_modules\broccoli-caching-writer\node_modules\broccoli-plugin\read_compat.js:61:34
    at lib$rsvp$$internal$$tryCatch (C:\MyApp\mycode\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:493:16)
    at lib$rsvp$$internal$$invokeCallback (C:\MyApp\mycode\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:505:17)
    at lib$rsvp$$internal$$publish (C:\MyApp\mycode\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:476:11)
    at lib$rsvp$asap$$flush (C:\MyApp\mycode\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:1198:9)

Could you please guide me as to where I should look to fix the issue.




get the local json server data in my ember application

I have created an one page web application using ember js. And I have installed the json.server in my local and created an json file(db.json). I really don't know how I can access my json.server in my application. I have used $.getJSON method and specified the json server URL http://localhost:3000/db.json(were my json server is running). But Its not any returning data. Please somebody give any suggestion of how I can access,edit my json file with ember js. Thanks in advance,




dimanche 27 septembre 2015

Rendering the results of controller actions in templates with Ember 1.13

First off, very new to Ember and especially the changes made to the role of controllers.

In my ember-cli 1.13.8 application, I have a controller action that finds items that were filtered through a user search. The problem is that the result of this search is never rendered on the template.

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({

 actions: {
   query: '',
   searchQuestions: function() {
     var filter = this.get('query');
     return this.get('model').filter(function(item) {
       return item.get('title').indexOf(query) !== -1;
     });
   }
 }
});

Template:

{{#each searchQuestions as |item|}}
  <p>{{item}}</p>
{{/each}}

My understanding is that searchQuestions should be available to the template. The action is correctly called and will run through the model that is returned from the route. I've console.logged out the method and it will intermittently print out -1 or 0 so it finds the matches. It just will not update in the template.

I have consulted the guides: http://ift.tt/1P0BZTJ as well as tried using {{outlet}} based up this question: Ember route not displaying template content.

If you can even recommend a good article for conceptually understanding the flow of an Ember application I'd be very appreciative.




Handling chained Promise in computed property

If I have a then() function on a promise it never resolves properly via a computed property

So this is OK,

  taxRate: computed(function() {
    return this.get('store').findRecord('tax-rate', { current: true });
  })

But this is not, (outputs [object Object] - the promise - in the htmlbars template)

  taxRateValue: computed(function() {
    return this.get('store').findRecord('tax-rate', { current: true }).then((taxRate) => {
      return taxRate.get('taxRateValue');
    })
  })

So what is the correct way to handling this without using an observer?




Ember TypeError: unsupported content on calling controller func

So I'm pretty fresh to Ember and encountered a TypeError exception saying 'unsupported content' and was able to find very little docs/content in general regarding the cause of this in relation to Ember. What triggers this exception is attempting to call functions from my controller in a template...

routes/dashboard.js

export default Ember.Route.extend({
  model: function(params){
    return ['Chart1', 'Chart2', 'Chart3']
  },
  setupController: function(controller, charts) {
    controller.set('charts', charts);
  }
});

controllers/dashboard.js

export default Ember.ArrayController.extend({
  something: function() {
    return 'something!';
  }
});

dashboard.hbs

{{#each chart in charts}} 
  <div class='widget well'>
    {{ chart }}
  </div>
{{/each}}
{{something}} 

While the template can successfully loop over the array passed in, attempting to call the function 'something' raises the error and prevents the template from loading. Any ideas what I'm messing up here?




Unclosed element ' ' in Ember.js 1.12.0 using if/else conditional helper

I have a newly-added section of code in my Ember.js/Handlebars template that looks like:

      {{#each day in week.days}}
        {{#if day.today}}
        <td class="active">
        {{else}}
        <td>
        {{/if}}
          <h5><b>{{day.mileage}}</b></h5>
          <br/>
          {{day.dayStr}}
        </td>
      {{/each}}

Where the day.today comes from an object populated like:

{
    ...
    today: dateEquals(new Date(), currentDate)
}

And I would like (in the little calendar I'm drawing) for that date to be highlighted if it's today.

But, when attempting to run this, the following error is emitted:

[18191:0927/082737:INFO:CONSOLE(12363)] "Uncaught Error: Unclosed element `td` (on line 14).", source: file:///path/to/project/js/libs/ember-template-compiler-1.12.0.js (12363)

Is this error coming from the pre-rendered template? Surely at runtime ("rendertime") there will only be either <td> or <td class="active">, but never both.

How can I resolve this issue?




Ember bind attribute using truth helper

I'm using Ember v1.13 and would like to render the checked attribute of an input element based on the result of an ember-truth-helpers expression. The following DID NOT work for me:

<input type="radio" checked={{(eq arg1 arg2)}}>

<input type="radio" checked={{if (eq arg1 arg2) true false}}>

Is there a way to do this, or do I have to resort to the following (which works)?

  {{#if (eq arg1 arg2)}}
      <input type="radio" checked>
  {{else}}
      <input type="radio">
  {{/if}}




samedi 26 septembre 2015

Ember-Cli import js without bower

I should import this plug-in that is not present in bower: ImageTiltEffect, in my ember-cli app. I already created the sub-directory in the vendor directory, imported this in my Brocfile and added "TiltFx": true in my .jshintrc file. About the last point I am not very sure if it is done in the right way, btw my question is: after these steps, how can I use this plug-in? How can I call its init function from my ember code? Thank you in advance for the answers!




Ember delay controller until authentication completes

I have a situation where I need to get some properties on the session, but I haven't found a successful solution to delay the loading of the route after a successful login.

So here's the deal - On the initial login, the this.get('session.currentUser') is not set. When I go to a different route and then come back, it is set correctly. If I'm on the phone-numbers route after login and then refresh the page, the phone-numbers load correctly because of the deferReadiness and advanceReadiness in the initializer. I can't deferReadiness before a login because the app is already loaded and ready.

The only part that's missing is that after the user logs in, it should load the numbers in the routes/phone-numbers.js, the last block of code pasted below. However, the myStoreId is not loaded because the session.currentUser is not set yet.

I've tried so many things to try and get this and am looking for some ideas. It's so close to working, but just missing one little piece.

// initializers/current-user.js
import Ember from 'ember';
import Session from 'simple-auth/session';

export default {
  name: 'current-user',
  before: 'simple-auth',

  initialize: function(container, application) {
    Session.reopen({
      setCurrentUser: function() {
        let appController = container.lookup("controller:application");

        // don't know how to check if the app is already ready
        try{
          application.deferReadiness();
          console.log('deferred');
        }catch(e){}

        if(this.get('isAuthenticated')) {
          console.log('running the isAuthenticated obs');

          let store = container.lookup('store:main');
          let _this = this;

          return store.find('user', 'me').then((user) => {
            // set the current user to be used on the session object
            this.set('currentUser', user);
          }).then(function(){
            // set the store for the current user
            store.find('store', {user: _this.get('currentUser.id')}).then(function(data) {
              _this.set('myStore', data.get('firstObject'));
              application.advanceReadiness();
            });
          })
        }
      }.observes('isAuthenticated')
    });
  }
};

// controllers/application.js
export default Ember.Controller.extend({
  myStore: Ember.computed(function(){
    // return the store object that is associated with the current user
    if(this.get('session.isAuthenticated')){
      if(this.get('session.myStore')){
        return this.get('session.myStore');
      }else{
        console.log(this.get('session.currentUser'));
        // this is where the problem is. The session.currentUser is not populated yet.

        this.get('store').find('store', {user: this.get('session.currentUser.id')}).then(function(data) {
          this.get('session').set('myStore', data.get('firstObject'));
          return this.get('session.myStore');
        });
      }
    }
  }),
});


// routes/phone-numbers.js
export default Ember.Route.extend({
  setupController: function(controller, model){
    this._super(controller, model);
    let myStoreId = this.controllerFor('application').get('myStore.id');

    if(!myStoreId){
      console.log(this.get('session.currentUser'));
      // there is no currentUser set on the session after login
    }else{
      this.store.find('store-phone-number', {'store': myStoreId}).then(function(numbers){
        controller.set('numbers', numbers);
      });
    }
  },
});




Ember - How to change the height of a panel from a controller?

I'm trying to change the height of a panel in an ember .hbs file from it's controller. I've seen lots of examples, but I can't seem to get things right. Here's a jsbin I put together for it, and following that is my code. Any help will be much appreciated. Thanks!

version: 1.13.8 node: 0.12.7 npm: 2.13.4 os: win32 x64

http://ift.tt/1gYfm4e

HTML

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://ift.tt/1sNUv3Z"></script>
        <link href="http://ift.tt/1K1B2rp" rel="stylesheet" type="text/css" />
        <script src="http://ift.tt/1InYcE4"></script>
        <script src="http://ift.tt/1JP22ba"></script>
        <meta charset="utf-8">
        <title>Ember Starter Kit</title>
        <link rel="stylesheet" href="http://ift.tt/1x2iORp">
        <script src="http://ift.tt/1VfQY14"></script>
        <script src="http://ift.tt/1gYfl0n"></script>
    </head>
    <body>
        <script type="text/x-handlebars">
        <div class="panel panel-primary" id="linkPanel" style="width:205px;">
            <div class="panel-heading">
                <h3 class="panel-title">Stuff</h3>
            </div>
            <div class="panel-body">
                Blah blah blah...
            </div>
            <div>
                <button style="margin: 10px;" {{action "addHeight"}}>Add Stuff</button>
            </div>
        </div>
        </script>
    </body>
    </html>

Controller (JS)

App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});

App.ApplicationController = Ember.Controller.extend({
  actions: {
    addHeight: function() {

// My goal here is to be able to increase the height
// of the panel "#linkPanel" from an action.

// In this version, I'm just trying to see
// if I can reference the panel (I can't.)

// In the commented out lines, I was trying
// to actually change it.

// Any help and/or advice will be much appreciated.

alert(document.getElementById('#linkPanel'));

//this.set('this.document.getElementById('#linkPanel').height',"500px");

//this.set('this.document.getElementById('#linkPanel').style.height',"500px");

//this.set('document.getElementById('#linkPanel').style.height',"500px");

//this.set('document.getElementById('#linkPanel').style.width',"500px")

     //this.set('document.getElementById('#linkPanel').style',"Height=500px")

    } 
  }
});




Filtering Emberjs Data by Attribute Properties

So I have an Ember-cli 1.13.8 application where I would like to view the questions without answers. Currently, I can filter searches based on attributes. For example, I can search for the "content" of questions because that is an attribute on the object.

Models:

answer:

export default DS.Model.extend({
  ...
  content: DS.attr(),
  question: DS.belongsTo('question', { async: true })
});

questions:

export default DS.Model.extend({
  ...
  answers: DS.hasMany('answer', { async: true }),
});

For example, this works to query attributes of the current model (question):

model(query) {
 return this.store.findAll('question').then(function(questions) {
   return questions.filterBy("content", query);
 });
}

But I cannot filter based upon the properties (in this case length) of the attributes of the model. I would like to filter based upon those questions which have no answers.

model() {
  return this.store.findAll('question').then(function(questions) {
    return questions.filter(function(item, index, enumberable) {
      return item.answers.length === 0;
    })
  });
}

I have consulted: Emberjs filter() versus filterProperty()

It seems that filterProperty() has been deprecated so examples such as: http://ift.tt/1MwACto are not helpful.




Comprehensive path to globally changing an Ember application name

I built an Ember app with CLI and 2.0 – it was an app for hats made of plants, so I named it "plant-hat."

A few months later, I realized that people didn't really like wearing plants on their heads, so I retooled it to sell "Shoes filled with worms." I think this time it'll really take off.

So, I want to rename the app and any important parts of it - as if I built it as "shoes-with-worms" from the beginning.

What steps do I take so that I don't miss anything.




Why does my Ember computed property on hasMany relationship not update?

I have an Ember Data model as:

export default DS.Model.extend({
  name: DS.attr('string'),
  friends: DS.hasMany('friend',{async:true}),
  requestedFriendIds: Ember.computed('friends',function(){
    return this.get('friends').then(function(friends){
      return friends.filterBy('status','Requested').mapBy('id');
    });
  })
 });

I have a route setup that uses it:

export default Ember.Route.extend({
  model: function(params){
    return Ember.RSVP.hash({
      memberProfile:this.store.find('member-profile', params.memberprofile_id).then(function(memberProfile)
      {
        return Ember.RSVP.hash({
          requestedFriendIds:memberProfile.get('requestedFriendIds'),
          UserId:memberProfile.get('user.id'),
          Id:memberProfile.get('id')
        });
      }),
    });
   }
 });

},

And htmlbars that utilize the route model. My computed property is always correctly called on a reload, but isn't refreshed on a user action 'Add Friend', which changes the store by adding a friend and the profile.friends' record like this:

actions:
{
  addFriend:function(profile_id,)
  {
    this.store.findRecord('member-profile',memberProfile).then(function(member){
      var friend = this.store.createRecord('friend',
      {
        member:member,
        status:'Requested',
        timestamp: new Date(),
      });
      friend.save();
      member.get('friends').pushObject(friend);
      member.save();
  }.bind(this));
}

}

Some notes: I've tried the computed property on 'friends','friends.[]'. The underlying data is correctly updated in the backing store (EmberFire). I've debugged into EmberData and I see that the property changed notifications invalidation code is called. This is only a selection of the code...

What am I missing...? Is there a better way to approach this?




Ember.js each-in helper not found

I'm using Ember.js 1.13.10

I get an Assertion Error helper 'each-in' could not be found

I searched the code in my bower component and indeed the each-in helper is not in the codebase

I don't understand why it is not there, it is in both the 1.13 and 2.0 guides and as far as I know ember 1.13 is identical to 2.0 minus the depreciations. each-in is a new feature which I can see on the github repo.




Ember.JS - toggleProperty toggling all items in list

I have a toggleProperty in the container to toggle a set of actions on each item. The problem is, when the toggle button on 1 item is clicked, every item is toggled, instead of the one that's clicked.

I would love to know how to toggle only the clicked item, not everything from the list.

I am using the ember-cli to build my application.

My category model:

import DS from 'ember-data';

export default DS.Model.extend({
  pk: DS.attr('string'),
  category: DS.attr('string'),
  products: DS.hasMany('product'),
});

My category route:

import Ember from 'ember';

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

My category controller

expand: function() {
  this.toggleProperty('isExpanded', true);
}

My template:

{{#each model as |i|}}
      <tr>
        <td>
          <a {{action 'expand'}}>{{i.category}}</a>
        </td>
        <td>
          {{i.pk}}
        </td>
        <td>
          {{#if isExpanded}}
            <button {{action "deleteCategory"}}>Edit</button>
            <button {{action "deleteCategory"}}>Delete</button>
          {{else}}
            <button {{action 'expand'}}>Actions</button>
          {{/if}}
        </td>
      </tr>
    {{/each}}

Since stackoverflow, is not letting me post without adding more text, I would also like to know how to show all the products associated with the category, on the same route (same page), by clicking on each category?

Cheers and thank you.




vendredi 25 septembre 2015

Push into the HTML header

What is the best way to ask the browser to prefetch a resource in an Ember.js application? The following code in the header of the HTML would do the trick:

<link rel="prefetch" href="http://ift.tt/1u6vnWS">

But I don't know what is the best way to push that code from within the Ember.js application to the HTML header.

I'm not talking about the boot time of an Ember.js application. I'm talking sometime during the usage. There are special scenarios where I know that the app will need a special resource after the next step. I'd like to preload that image/data/whatever at that time.




Why doesnt an ember observer fire on arrays?

I am trying to listen to specific property on every element in an array and get a result from that. However, updates dont appear to happen properly.

var emptyEmberObjectClass = Ember.Object.extend({});
var container = Ember.Object.extend({
  data: Ember.A([
    emptyEmberObjectClass.create({yo:1}),
    emptyEmberObjectClass.create({yo:2}),
    emptyEmberObjectClass.create({yo:3})
  ]),
  computedData: Ember.computed('data.@each.yo', function(){
    var sum = 0;
    this.get('data').forEach(function(data){
      sum = sum + data.yo;
    });
    return sum;
  }),
  test: Ember.observer('computedData', function(){
    Ember.$('#a').html('woohoO!');
  })
}).create();
var existingItem = container.get('data');
existingItem.objectAt(0).set('yo', 50);

http://ift.tt/1iRtSN4

As you can see, the text field still says 'start' and doesnt get updated to 'woohoO!'.

Any help will be greatly appreciated.




Getting the value of element clicked on in Emberjs

I have a series of labels that I would like to retrieve the text from when the user clicks on them. I thought the jquery might be doable in Emberjs:

$(this).attr('text');

This however, doesn't work with Ember. My component view is this:

<ul class="list-inline">
  {{#each model as |model|}}
    <li {{action "sendToInput"}} class="label label-default">{{model.name}}</li>
  {{/each}}
</ul>

I would like to retrieve that model.name value via the action "sendToInput".

In my component js file I have tried:

actions: {
  sendToInput() {
    $(this.target).attr('text');
  }
}

I have also tried:

this.innerHTML;
$(this).text();
this.get('text');
$(this).val();

I have also opened up the console and dug through this and cannot seem to find where they store the element clicked on.

The documentation doesn't mention this and there's no issue I can find on the Github for ember-cli.

Thanks.




helper returning an object not scalar value expected

Thought I'd create a if-then-else helper which looks like this:

import Ember from 'ember';
export function ifThenElse(param, ifTrue, ifFalse=null) {
  return Boolean(param) ? ifTrue : ifFalse;
}

export default Ember.Helper.helper(ifThenElse);

And then when using my component I can do the following:

{{my-nifty-component class=(if-then-else pigsHaveWings 'wake-up' 'good-answer') }}

Well the problem I'm having is that my helper is not very helpful and the HTML/DOM result is:

<div class="[object Object] ember-view"></div>

Can someone please help me with my helper?