samedi 31 octobre 2015

Data store return only one record in ember

I'm trying to view user list in a template.But it retrieves only one(last) record i have entered.Why is it returning a single record? Is it a data-store cache problem?Following is the approach that i have followed

templates/userlist.hbs

{{#each item in model}}
{{#link-to 'userlist.edit' item.id}}edit:{{item.userName}}{{/link-to}}
{{/each}}

routes/userlist.js

    import Ember from 'ember';

    export default Ember.Route.extend({

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

    });

model/user.js

import DS from 'ember-data';

export default DS.Model.extend({


    docType:DS.attr('string'),
    firstName:DS.attr('string'),
    role:DS.attr('string'),


    userName:DS.attr('string'),
    password:DS.attr('string'),

    lastName:DS.attr('string'),
    mobileNo:DS.attr('string'),
    landNo:DS.attr('string'),
    address:DS.attr(
        {
        no:'string',
        street:'string',
        city:'string'
    }
    ),

    nicNo:DS.attr('string'),



}); 

api/user.js

module.exports.getAllUsers=function(req,res) {
    UserModel.find({},function(err,docs) {
        if(err) {
            res.send({error:err});
        }
        else {
            res.send({user:docs});
        }
    });
};

app/routes.js

router.route('/api/users').get(function(req,res){users.getAllUsers(req,res)})
                              .post(function(req,res){console.log(req.body);users.addUser(req,res);});




Ember CLI is too slow to use it

I can't use ember CLI because is too slow. How should I use something that re-compiles in every change and takes 25 seconds?

Build successful - 22102ms.

Slowest Trees                                 | Total               
----------------------------------------------+---------------------
SassCompiler                                  | 10153ms             
ConcatWithMaps                                | 3954ms              
BroccoliMergeTrees                            | 1906ms              
BroccoliMergeTrees                            | 1811ms              

Slowest Trees (cumulative)                    | Total (avg)         
----------------------------------------------+---------------------
SassCompiler (1)                              | 10153ms             
ConcatWithMaps (4)                            | 5154ms (1288 ms)    
BroccoliMergeTrees (4)                        | 3759ms (939 ms)     

My project iq empty, I'm using only ember sass as dependency and all my routes, controllers, models and templates are empty.

Is this normal? Can't I turn off something? For example the live reload I'm not using, how could I turn off this?

related: http://ift.tt/1WqdzDd




Ember.js: "Can't find variable: exports"

I started compiling my Ember.js templates server-side using the "ember-template-compiler.js" file mentioned here.

After compiling my templates and transpiling the output with Babel, I get a file which contains all of my templates assigned to an object called "export". Here are the first few lines:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports["default"] = Ember.HTMLBars.template((function () {
  return {
    meta: {
...

Now I've integrated jQuery, "ember.prod.js" and that file within the front-end. I thought it would work, but the only thing I get from the console, is:

ReferenceError: Can't find variable: exports

Why is "exports" not defined?

P.S.: Usually, I would use "ember-cli" for all of this. But in my current project, I need to do everything by myself (please don't ask, why).

But it should work, am I right? I mean, I did it exactly like it was stated here.




emberjs - refactor to component helper

I am migrating some code from ember 1.7.1 and I created my own component helper before there was one in the form of a handlebars helper:

Ember.Handlebars.registerHelper('renderComponent', function(contextPath, propertyPath, options) {
  var context, helper, property;
  context = Ember.Handlebars.get(this, contextPath, options);
  property = Ember.Handlebars.get(this, propertyPath, options);
  helper = Ember.Handlebars.resolveHelper(options.data.view.container, property.component);
  options.contexts = [];
  options.types = [];
  property.bindings.forEach(function(binding) {
    options.hash[binding] = binding;
    options.hashTypes[binding] = "ID";
    options.hashContexts[binding] = context;
  });

  return helper.call(context, options);
});

The helper is called like this:

  {{#each column in columns}}
    <td>
      {{renderComponent item column}
    </td>
  {{/each}}

And would create components from a configuration like this:

App.IndexController = Ember.Controller.extend({
  columns: Ember.A([
   {
      heading: "Heading",
      binding: "name",
      route: "company"
    },
    {
      heading: "Address",
      binding: "address"
    },
    {
      heading: 'full',
      component: 'full-contact',
      bindings: ['name', 'address']
    }
  ])
});

How can I achieve the same thing with the component helper?

I'm thinking specifically about passing arguments and bindings to the component helper? How is that done?




vendredi 30 octobre 2015

authenticationSession does not populate user to session.secure ember-simple-auth testing

"ember-cli-simple-auth-testing": "0.8.0", Hi I have a protected route under which all routes that needs authentication is nested.

On authentication I populate current user to get extra information of current user like rights.

  _populateCurrentUser(){
    var self = this;
    const user_id = this.get('session.secure.user.id');
    const user_type = userType(parseInt(self.get('session.secure.user.type')));
    return self.store.find(user_type,user_id).then(function(user){
        self.set('session.currentUser',user);
      if(Ember.isEmpty(user)){
        self.transitionTo('login');
      }
    },function(err){
        console.log("There was some error getting currentUser"+err);
    });
  }

I call the above _populateCurrentUser() in before model of protected route.

beforeModel(transition,queryParams) {
        var self = this;
        self._super(transition,queryParams);
    if (self.session.isAuthenticated) {
       return this._populateCurrentUser();
    }
  },

for testing purpose I need to populate the session.secure.user.id

test('I can create a story',function(assert){
  var user =  server.create('writer');
  var sessionWriter = {
    secure: {
      user:{
        id: 1,
        type: 'writer'
      }
    }
  };
  authenticateSession(this.application,sessionWriter);

The above authenticateSession does not add the session sessionWriter and hence my _populateCurrentUser() fails as self.get('session.secure.user.... is empty.




Why does data from a model not render in an Ember template's {{#each}} loop?

Data that seems successfully loaded into my model does not seem to be used when rendering a page template in Ember 2.1.0. How can I get the data that is shown to me in Ember Inspector to be successfully called by the page template?

I have a model:

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

  App.IndexRoute = Ember.Route.extend({  
    model: function() }
     return this.store.findAll('part')
    }
  });

and a template:

{{appName}} v {{appVersion}}
<ul>
  {{#each part in model}}
        <li>{{part.name}}</li>
    {{else}}
        none found...
  {{/each}}
</ul>

and in my Ember Inspector I see data (loaded via RESTAdapter): Data properly loaded loaded with unique IDs and part names

But the template when rendered always says, "none found..." and never lists the data that appears to have been successfully loaded. I have tried multiple variations of the {{#each}} tag.

A standard app controller loads data into the template just fine (calling {{appName}} or {{appVersion}}):

App.ApplicationController = Ember.Controller.extend({
  appName: "My App",
  appVersion: "1.0",
});

Ember 2.1.0, EmberData 2.1.0, EmberInspector 1.9.3




Ember 2.1.0 render partial if index page else another partial

In my templates/application.hbs I would like to be able to set a condition to check if it is my index page I render a navigation for it, else it would render another set of navigation for in-app pages. The same for my footer. What is the best way to check this? Also, whether a user is login or not doesn't matter.

My research has lead to outdated code or convention. I'm also completely new to Ember so any help would be very much appreciated.




How to transition to route in Ember from global context?

I am integrating a chrome extension with an ember app. I have some chrome extension code in my app.js file:

window.sendToExtension = (message, callback) => {
  chrome.runtime.sendMessage(extensionId, message, (response) => {
    console.log('got response from extension!!', response)
    if (response.path) {
      //Here I need to tell the ember app the transition to the given path
    }
  })
}

this refers to window so I can't just call this.transitionTo. How can I transition to the route name the extension has told me to?




how can I figure out what version of ember a site is running?

If I navigate to a site that is using Ember, is there anyway for me to get the version information? I have access to the console and dev tools but this is for a production build without sourcemaps, etc...

Thanks!




Ember js - file upload component - force change event to fire on during second attempt to upload the same file

I am using the Ember Uploader component to allow users to upload a .txt file.

This file has to be formatted in a very specific way, and the upload cannot be allowed if the file is not formatted correctly.

The component first reacts to the change event, which watches for a new file being selected.

This sets the property 'files' to the selected file, which causes the function filesDidChange to run.

In filesDidChange, the file is read and checked for formatting errors. If it finds errors, it tells the user to update the file and try again.

Everything works perfectly on the first attempt. The problem is that when you try to re-upload the edited file, the component does not recognise this as a change event- the alert("Hello World") doesn't fire.

I assume this is because the same file has been selected.

I've tried setting 'files' to null at the end of the filesDidChange function, but that has no effect. This makes sense, as the change event watches the element, rather than a property.

How can I get the change event to fire, even if the same file is selected to upload on the second attempt?

change: function(e) {
    alert("Hello World");
    var input = e.target;
    var selectedFiles = input.files;
    if (selectedFiles) {
      this.set('files', selectedFiles);
    }
  },
filesDidChange: function(files) {
    //Reads the text file using the FileReader API.
    //Checks that the file is correcty formatted.
    //Prevents the upload and displays an error message if the file format is wrong.
    //Asks the user to fix the errors and try to upload the same file again.
}.observes('files'),



How to call another file with help of JSON in ember?

        **jsonfile:**
        {
        "themingtests":[  
              {  
              "id"  :1,
              "path": "EmberTest/WebContent/json/themingtests.json"
              }
           ]
         }

    **HTML file:**
    <script type="text/x-handlebars" id="index">
        {{#each item in model}}
    {{item.path}}
    {{/each}}

**JS File:**
App.Themingtest =DS.Model.extend({
    path: DS.attr('string'),

});

I'm not able to read a file on that particular path . Is there any other way then kindly please Suggest !!




Carousel image changes with category in ember js

I have designed a image carousel and navbar above it with different category. the plan is whenone of the category clicked the images in carousel changes.the category are etch from backend and displayed in navbar.How do I relate it to carousel with each category.I am using ember js(1.13.0).




Ember continue create model even when request error

I have ember model like this:

import DS from 'ember-data';

export default DS.Model.extend({        
    sportType: DS.attr('string'),       
    fallbackLogo: function(){
        return 'assets/images/markers-png/marker-'+this.get('sportType').toLowerCase()+'-gray.png';
    }.property('sportType')
})

but even the request for find() got response error

GET http://ift.tt/1KJEQK9 404 (Not Found)

the model still try to create itself thus trigger error

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

how i can handle request error?




Ember component and dynamic attributes over iteration

How can I add support to my custom Ember component for appending dynamic attributes and also action? I have my custom component as

{{my-radiobutton name='myName' value='RadioButton1' selection=this.selectedRadio}}

Now I want to iterate over API response and have dynamic attributes in my template as well as action support as below;

{{#each model.myApi as |myApi|}}
{{#if someCondition}}
{{my-radiobutton name='myName_{{myApi.someId}}' value='someAction_{{myApi.someId}}' selection=this.selectedRadio {{action 'actionClicked'}}}}
{{else}}
{{my-radiobutton name='myName_{{myApi.someId}}' value='someAction_{{myApi.someId}}' selection=this.selectedRadio {{action 'actionClicked'}}}}
{{/if}}
{{/each}}

Is it possible to do that?

PS: I do not have control over the custom component my-radiobutton, since it is kind of common/external, so I'll prefer anything in the template or my controller




jeudi 29 octobre 2015

Binding a class to DOM setting Timeout in Ember

I have an animation working when the class "fa-counter" is added to the DOM.

I want that the animation start working after 3 seconds i land in the page. How can i control that in ember?

I have found Ember.run.later an option to use , but i struggle on how to implement it.

The code

Html

{{#if isAnimate}}
    <i class="fa fa-cog fa-fw big fa-counter"></i>
{{else}}
    <i class="fa fa-cog fa-fw big"></i>
{{/if}}

So if it isAnimate the class fa-counter makes start the animation

In my controller by default isAnimate is false

var MenuController = Ember.ObjectController.extend({
    isAnimate: false,
    startWatchingAnimation: function(controller){
        var self = this;
        Ember.run.later(function(){
          self.set('isAnimate', true);
        }, 1000);
    },
});

I have thought also to access to access the scoped JQuery object with the this.$() method.

Html

<i class="fa fa-cog fa-fw big"></i>

Controller

var MenuController = Ember.ObjectController.extend({
    isAnimate: false,
    startWatchingAnimation: function(controller){
        Ember.run.later(this, function(){
            this.$('.fa').addClass('.fa-counter');
        }, 500);
    },
});

No one of the two methods really work, how can i achieve that?




consuming json in ember and rest-serializer

i'm trying to display in my ember app the data but i can't serialize json which http://ift.tt/1n31l1Y give me. i have it locally but the format is the same. i put in my serializers/application.js this:

export default DS.RESTSerializer.extend({
  normalizePayload: function(type, payload) {

    if (type.toString() === 'App.Posts') {
       return { posts: payload };
    }else{
         console.log(type);
         console.log(payload);
    }
  }
});

in my console, when i read "console.log(type)", it shows to me the array with the Objects (posts) Array [ Object, Object, Object, Object, Object, Object, Object, Object,Object, Obj... and more] and console.log(payload) is undefined thanks if you help me




Set position of a Ember component as it is generated

I'm trying to make a drag and drop UI in my Ember app. A person has a component displaying various attributes.

I want the component to be dragged and positioned on a grid. The position the component is dragged to is then saved, as an attribute of the model. No problem.

My problem is that on loading the page, I want to position each component using those saved position attributes. The JQuery for positioning it etc I'm happy that I can work out, I just don't know where to put it.

My two thoughts are:

  1. Once the route has loaded, go through and reposition each of the components. (not the best sounding option)
  2. Is there an event specific to the successful generation of a component? Each component would then be created and positioned immediately in turn. Hopefully then I could maybe also pass in the position attribute. Any details or suggestions on this option would be much appreciated.

Thanks




Ember.js Acceptance Testing not waiting for asynchronous data operations

When using the Emberfire (Firebase) adapter, I'm getting various errors that indicate the tests are not waiting for data operations to complete.

eg: Error: Assertion Failed: You can only unload a record which is not inFlight. when I try to create, check, and then delete a record

Also:

FIREBASE WARNING: Exception was thrown by user callback. Error: Called stop() outside of a test context at Object.extend.stop (http://localhost:4200/assets/test-support.js:3000:10) at exports.default._emberTestingAdaptersAdapter.default.extend.asyncStart

These errors do not occur while manually navigating through my app, nor when using the standard ember data adapter.

What is causing these errors and how do I avoid them?




Uncaught TypeError: this.transitionTo is not a function

I just upgraded my application to ember 2.1 and am getting this error in my web browser console:

Uncaught TypeError: this.transitionTo is not a function

In my url, I have a variable named direction:

http://localhost:4200/plates/new?direction=plates

Then I build this into my controller:

export default Ember.Controller.extend({
    queryParams: ['direction'],
    direction: null,
    actions: {
        lastpage(){
            this.transitionTo(this.get('direction'));
            },
       save(...){
            },  

        },  
    }); 

This used to work before my upgrade. What depreciated / how do I fix this error?




How to delete / destroy record in rails API backend from an ember.js frontend

I have a rails API backend that contains various records, and I would like to be able to delete them from the ember.js frontend. I am able to display the records using ember.js but when I click the delete button that I added via ember the record is not being deleted within the rails backend. I am not even seeing any activity from the rails server in the console when I click the delete button.

ember

// app/routes/index.js

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        return this.store.find('csv-file');
    },
    actions: {
        delete(csvFile) {
            // debugger;
            csvFile.destroyRecord();

            // csvFile.save();
        }
    }
});

// app/models/csv-file.js

import DS from 'ember-data';

export default DS.Model.extend({
    csv_file_filename: DS.attr('string')
    // id: DS.attr('int');
});

// app/templates/csv-files/index.hbs

<h3>Hi CSV Files</h3>
<ul>
    {{#each model as |csv|}}
        <li>
            {{csv.id}} - {{csv.csv_file_filename}}
            <button {{action 'delete' csvFile}}>Delete</button>
        </li>
    {{/each}}
</ul>

rails

# csv_files_controller.rb

# DELETE /csv_files/1
  # DELETE /csv_files/1.json
  def destroy
    @csv_file = CsvFile.find(params[:id])
    if @csv_file.destroy
      render :json => { :head => ok }, status: 200
    else
      render json: {error: "csv file could not be deleted."}, status: 422
    end
  end




Ember router can transition to but not handle a url

Using Ember 2.1.0 with EmberData, I'm making a small blogging app. It has two routes

Router.map(function(){
  this.route("posts": "/");
  this.route("post", {path: '/:seo_friendly_link'});
}

The seo_friendly_link looks like this

 /2015/10/28/my-blog-post-title/

In the index route, I display a list of posts with links to each post. If I click a link, the Ember app will transition to the post that I clicked on. I emphasize transitionto-- the routing goes through that method in Ember router.

The problem:

However, if I drop that same url into the browser, I get an UnrecognizedURLError (before the model or even the beforeModel hook are called for the post). If I drop the url into the browser, the routing goes through the handleURL method on Ember Router, which doesn't happen if I click a link from the homepage. So my Ember app can transition to my seo_friendly_link, but not handle that url.

I'm not sure why.

Question: How can I create a route to recognize that link?

Code

There is a property on the Post model called

   seo_friendly_link: DS.attr('string')

In /routes/post, I call the serialize method to create that parameter from the model property

  serialize: function(model, params){
     seo_friendly_link: model.get("seo_friendly_link");
  }




How to Force a Reload from the Server?

I have a page that gets a default list of data from the server, and this page also has a search box that, when run, updates a query parameter and returns a new list of data to the same page. This works fine.

However, when I clear the search (either through an action or by hitting "back" in the browser), I want to get the default data fresh from the server, replacing whatever the search results were.

I think I have this most of the way there, because clearing out the query parameter does cause findAll() to ask the server for data again, and that also gives back the right data, but the store keeps all the previously retrieved records from the search, so now the user sees both the default set plus the records they got back from the search.

So, how do I force Ember Data to use what comes back from the API and overwrite whatever it had in the store?

Here's my route code. Despite having reload: true and refreshModel: true, it appears that neither are actually happening:

model: function(params) {
  if (params.q) {
    return this.store.find('project', params);
  } else {
    return this.store.findAll('project', {reload: true});
  }
},
queryParams: {
  q: {
    refreshModel: true
  }
},

Thanks in advance!




jquery val update with trigger change of input field not seen by ember

I have a Chrome extension that takes a userid/password and then passes it to a content script that runs in another tab to log in to that site. The content script uses jquery to programmatically update the userid and password fields and then click the login button. This worked fine until the login screen was rewritten with Ember.

Now, the login button is not active until inputs are seen in the userid/password fields. The jquery .val() function updates the fields but the app apparently has an Ember bind for change to activate the login button when both fields have text. The .val() update does not trigger the change. I have tried two approaches and can not get either to work.

  1. I added .trigger('change') but that doesn't seem to get noticed by ember. At least the login button does not become active.

  2. I tried adding Ember.View.views['emberxxxx'].set() which works in the debug console but not in my Chrome content script. I get error "TypeError: Cannot read property 'views' of undefined". I wonder if I need to define something more to get this statement to work. I do have ember.prod.js defined in JS in my manifest file, but nothing else. I am very Ember-challenged.

Any advice is appreciated!

Thanks, Doug




not ok 1 PhantomJS exited unexpectedly when running `ember test` on CI

Since updating to ember-cli 1.13.8 and Ember 2.0.0 (from 1.13.1 / 1.12.x) I can't get the test suite to run on CircleCI, because of the error:

not ok 1 PhantomJS - Browser "phantomjs /home/ubuntu/app-name/node_modules/ember-cli/node_modules/testem/assets/phantom.js http://localhost:7357/7887" exited unexpectedly.
1..1
tests 1
pass  0
fail  1
npm ERR! Test failed.  See above for more details.
npm test returned exit code 1

It used to work before and what is weird, it works locally (OS X El Capitan, PhantomJS 2.0). On CircleCI it also runs on 2.0 version which is installed the following way:

$ sudo apt-get update; sudo apt-get install libicu52
$ curl --output /home/ubuntu/bin/phantomjs-2.0.1-linux-x86_64-dynamic http://ift.tt/1PWWUr1
$ chmod a+x /home/ubuntu/bin/phantomjs-2.0.1-linux-x86_64-dynamic
$ sudo ln -s --force /home/ubuntu/bin/phantomjs-2.0.1-linux-x86_64-dynamic /usr/local/bin/phantomjs

Tried also downloading it from the Travis, but still the same thing happened.

Any idea what's the cause and how to solve it?




Stubbing service injected in initializer for testing components in Ember 2.1

Before currentUser was injected as a service in auth-button view model.

{{#if currentUser.loggedIn}}
  {{#link-to 'auth.logout'}}{{t 'auth.logout'}}{{/link-to}}
{{else}}
  {{#link-to 'auth.login'}}{{t 'auth.signIn'}}{{/link-to}}
{{/if}}

export default Ember.Component.extend({
  currentUser: Ember.inject.service('current-user'),
});

With this setup, I could mock currentUser in auth-button test:

import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';
import instanceInitializer from 'ntfrontend/instance-initializers/ember-intl';

const userStub = Ember.Service.extend({
  loggedIn: false,
});

moduleForComponent('auth-button', 'Integration | Component | auth button', {
  integration: true,
  setup() {
    this.register('service:current-user', userStub);
    this.inject.service('current-user', { as: 'currentUser' });
    instanceInitializer.initialize(this);
    const intl = this.container.lookup('service:intl');
    intl.setLocale('en-us');
  }
});

test('should render auth links', function(assert) {
  assert.expect(2);
  this.render(hbs`{{auth/auth-button}}`);
  assert.equal(this.$().text().trim(), 'Sign In');

  this.set('currentUser.loggedIn', true);
  this.render(hbs`{{auth/auth-button}}`);
  assert.equal(this.$().text().trim(), 'Logout');
});

As I need to have access to currentUser in many places, currentUser is now injected in initializer:

export function initialize(App) {
  App.inject('component', 'currentUser', 'service:current-user');
  App.inject('route', 'currentUser', 'service:current-user');
  App.inject('controller', 'currentUser', 'service:current-user');
}

export default {
  name: 'current-user',
  initialize: initialize,
};

With this setup the second case fails (view is not rerendered):

test('should render auth links', function(assert) {
  // actually the stub is not needed as `currentUser` defaults to falsy value

  this.set('user.loggedIn', true); 
  this.render(hbs`{{auth/auth-button}}`);
  assert.equal(this.$().text().trim(), 'Logout'); // still `Sign In`
});

How to go about this kind of dependency injection? Should I manually inject it into App namespace?




Unit Testing Ember Services that Fetch Data

I have an ember service thats primary concern is to fetch data for a specific model and the descendants of the model. The reason I am using this in a service is because the route for this particular type is using a slug which is not the primary key and therefore needs to do a store.query instead of store.find. When we fetch this model I have some logic that peeks the ember store to see if we can load it from there before going to the api query. Also this vendor is watching for the slug change and updating the current model based on that.

The problem I am having is that this seems to have very little documentation when it comes to how to test a thing like this. In fact I don't see a section on testing services anywhere in the guides here http://ift.tt/20d8nr7

This is a snippet of the service in question.

import Ember from 'ember';

export default Ember.Service.extend({
    _vendorSlug: null,
    vendor: null,

    vendorSlug: function (key, value) {
        if (arguments.length > 1) {
            if (this._vendorSlug) {
                return this._vendorSlug;
            }

            this._vendorSlug = value;
        }

        return this._vendorSlug;
    }.property(),

    ensureVendorLoaded: function (slug) {
        var service = this,
            vendorSlug = slug || service.get('vendorSlug'),
            currentVendor = service.get('vendor'),
            storedVendor;

        if (!Ember.isNone(currentVendor) && (vendorSlug === currentVendor.get('slug'))) {
            return new Ember.RSVP.Promise((resolve) => {
                        resolve(currentVendor);
                    });
        } else {
            var storedVendors = service.store.peekAll('vendor').filter((vendor) => { 
                return vendor.get('slug') === vendorSlug;
            });

            if (storedVendors.length) {
                storedVendor = storedVendors[0];
            }
        }

        if (!Ember.isNone(storedVendor)) {
            service.set('vendorSlug', storedVendor.get('slug'));

            return new Ember.RSVP.Promise((resolve) => {
                    resolve(storedVendor);
                });
        }

        return service.store.queryRecord('vendor', {slug: vendorSlug}).then((vendor) => {
            service.set('vendor', vendor);
            service.set('vendorSlug', vendor.get('slug'));

            return vendor;
        });
    },

    _vendorSlugChanged: function () {
        if (this.get("vendorSlug") === this.get("vendor.slug")) {
            return;
        }

        this.ensureVendorLoaded();
    }.observes('vendorSlug')
});




How do I resolve an expected Ember.PromiseProxyMixin rejection?

I ran into this odd case when I was attempting to use the PromiseProxyMixin to clean up my templates. One of the situations was when I had a component that rendered a list after a search is completed with our API. The searching was debounced because it triggers when the search term changes. I then wrote a cancelation mechanism that would reject the last pending promise before making a new one this.set('promise', newPromise). I started noticing that these rejected promises were being spit out to our logging service because the Ember.onerror were trapping all unhandled rejections even though the Component I had expected that.

Normally in a promise chain you can avoid unhandled errors by making sure you place a .catch() at the end of the chain. However, I don't know how to do this if the promise is meant to be used in a PromiseProxyMixin.

Here is a JSBin that illustrates the problem with expected rejections in a PromiseProxyMixin.




Does focusOut work differently in FireFox than in other browsers?

In my application, I have a div with tabindex='0', with this kind of structure:

<div class='parent' tabindex='0' bubbles=false>
    <div class='child1'>
    </div>
    {{#if property}}
        <div class='child2'>
            <div id='listitem1'>
            </div>
            <div id='listitem2'>
            </div>
        </div>
    {{/if}}
<div>

This is an ember application, so the {{#if}} comes from handlebars. I used the focusOut property for this entire component to hide child2 on focusOut. Even if you're not familiar with Ember.js, the idea is that the focusOut event handler is bound to the main element of the component. In this case: parent.

In Chrome, IE and Safari, when I click any of the list item divs inside child2, the parent retains focus. In FireFox, specifically the latest one (41.0.2), clicking any element inside parent will cause parent to lose focus.

This leads me to believe that FireFox handles focusout differently. If so, how can I make sure that on clicking any element inside a focused parent, the parent will stay focused?

I have to mention a few things:

  • I cannot accept a solution involving a listener on the click event itself. (As in listen for click on the entire document and see if the clicked target is the parent div).
  • I cannot use 'blur'. It causes this same issue to appear in all browsers.



Ember: hooking into ActionHandler#send

I am trying to instrument this.send() in Ember, by hooking into ActionHandler#send as follows:

Ember.ActionHandler.reopen({
  send() { console.log("hooked"); this._super(...arguments); }
}

When I call this from app.js, as the app is starting up, it works. When I call it from an initializer, it does not. When I call it after the app starts up, such as from the application controller, it doesn't work either. In both cases where it doesn't work, if I trace into a this.send() call, it goes directly into the original implementation of send.

I have a suspicion this has something to do with the way mixins are used when instantiating objects, but otherwise I'm stumped.




Ember js display each item in javascript array in {{#each}} helper

I am creating the following array variable in an ember component, and passing it to the controller for my template file.

var errors = [
0: "Line 2 needs a tab separator."
1: "Line 42 is empty."
2: "Line 43 is empty."
3: "Line 44 is empty."
4: "Line 45 is empty."
5: "Line 46 is empty."
6: "Line 47 is empty."];

In the controller I am setting a property to this array value:

this.set('errorList', errors);

I can then display the array in the template file:

{{controller.errorList}}

The problem is that the errors display as one long string like so:

Line 2 needs a tab separator.,Line 42 is empty.,Line 43 is empty.,Line 44 is empty.,Line 45 is empty.,Line 46 is empty.,Line 47 is empty.

Is it possible to use an {{#each}} helper to display each item, and thus become able to to add in HTML tags- eg:

<ul>
{{#each **** as |***|}
 <li>***Display each individual error here.***</li>
{{/each}}
</ul>

Would it help if I was able to convert the array variable into a JSON object?




Handlebars not rendering based on js code

In my Ember app, I have the following code in my Handlebars template (partial code)

<input type="radio" class="warningActionExcl" name="warningAction_{{warningDetails.someId}}" {{action 'warningActionClicked'}} data-someId="{{warningDetails.someId}}" />   

Also in the corresponding controller class, I have

var isExclude = $(event.target).attr('class');
if (isExclude == "warningActionExcl") {
    //do something
} 

Now the template renders properly with the above. But if I update my template code as (i.e. mismatched class name with what the JS is checking for..warningAction V/s warningActionExcl)

class="warningAction"

the template does not render entirely. But it does not give any Javascript error.

I am not sure why this is the case, as I thought there is no checking with JS code while rendering the template.

Please suggest.




mercredi 28 octobre 2015

Ember.$.param removes spaces from params and adds '+' sign

I am stuck with a problem. For instance if i have a json Object parameter like param = {abc: 'my example parameter'} and have an api like var api = 'api/xyz?'

now I want to append the parameters to my api, so I am using the following line of code

var url = api + Ember.$.param(param || {});

but the problem with this method is that when I use Ember.$.param(param || {}) and if the param contains spaces it results in as url = 'api/xyz?abc=my+example+parameter' instead of var url = 'api/xyz?abc=my example parameter'

I know I can always right a custom function for this but I want to do it using the Ember's inbuilt functionalities, so is there any such Emberish way in which I can get the required api call without '+' in the parameter for spaces.




App.ArticleAdapter =DS.FixtureAdapter.extend({}); extend undefined in ember js-Uncaught TypeError: Cannot read property 'extend' of undefined

i am new to emberjs. when i am trying to extend DS.FixtureAdapter i am getting error like'Uncaught TypeError: Cannot read property 'extend' of undefined' here is my

App = Ember.Application.create(); App.ArticleAdapter =DS.FixtureAdapter.extend({});




How should I specify a minimum version of Ember.js in my ember-cli addon?

I've just published an ember-cli addon using features available only in projects that have updated to Ember 2.x by making the required changes to their package.json and bower.json.

How should I specify that the addon will only work with Ember 2.x?




How to set an application wide variable? (on app controller?)

I am using the latest Ember, 2.1, and am wondering how to set some application wide variables, such as user id, username, email, etc, presumably on the application controller.

While ember applications have tons of files, I haven't really done a lot yet, I'm somewhat confident I'm sharing just the right code. I don't have a login route file. I have the ember simple auth plugin installed, but I'm not actually using/invoking it any special way, except for mixing it into my application route:

import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin)

My router:

this.route('login')

My login template:

<button {{action 'forceLogin'}}>Force login of devinrhode2@gmail.com by clicking this action button</button>
<p>Your account id is: {{account_id}}</p>

My login controller:

export default Ember.Controller.extend({
  actions: {
    forceLogin: () => {
      var data = {
        "account_id": 123,
        "email":"devinrhode2@gmail.com",
        "name":"Devin Rhode"
      }
      this.setProperties(data)
    }
  }
});

I have the forceLogin controller action being called, but, the {{account_id}} is not populating into the template. How could I get the account_id to render back into the template? How could I make the account_id globally accessible to my ember application by calling this.get('account_id') wherever I need it?

Currently I get the error:

 Cannot read property 'setProperties' of undefined




Error for one hasMany but not another. Makes no sense

I have a model "Group" that has some hasMany relationships "members" and "links". I have a controller that adds a new group but i get the following error on save

"Assertion Failed: A App.Group record was pushed into the store with the value of links being '{}', but links is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer."

I can fix this by returning an empty links array in the response json but i don't necessarily want this included and i don't understand why i get this error for links but not for members as that isn't included in the response either.

App.AddGroupController = Ember.ObjectController.extend({
    needs: ['application'],
    actions: {
        submitForm: function(){
            var self = this;
            var model = this.get('model');
            self.send('showLoading', 'Saving');
            model.save().then(function(){
                self.send('hideLoading');
                //Go to the groups list
                self.transitionToRoute('groups');
            },function(error){
                self.send('hideLoading');
                console.log(error);
                //Must supply reject callback, otherwise Ember will throw a 'backend rejected the commit' error.
            });
        }
    }
});

App.AddGroupRoute = App.AuthenticatedRoute.extend({
    model: function(){
        return this.store.createRecord('group');
    }
});

App.Group = DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('string'),
    members: DS.hasMany('groupMember'),
    links: DS.hasMany('groupLink'),
});

App.GroupLink = DS.Model.extend({
    title: DS.attr('string'),
    link: DS.attr('string'),
});

App.GroupMember = DS.Model.extend({
    first_name:      DS.attr('string'),
    last_name:       DS.attr('string'),
    email:           DS.attr('string'),
    profile_picture: DS.attr('string'),
});

Response from save:

{
   "group":{
      "id":26,
      "title":"Test Group",
      "description":"Dummy group description",
   }
}

Im using:
Ember : 1.9.1
Ember Data : 1.13.14




Class Bindings dynamically with Ember.run.later

I want to add an animation after few seconds i have landed in a page

I need to bind a class to achieve it

This is my markup

{{#if isAnimate}}
    <i class="fa fa-cog fa-fw big fa-counter"></i>
{{else}}
    <i class="fa fa-cog fa-fw big"></i>
{{/if}}

So if it isAnimate the class fa-counter makes start the animation

in my controller by default isAnimate is False and i am trying to use Ember.run.later

var MenuController = Ember.ObjectController.extend({
    isAnimate: false,
    startWatchingAnimation: function(controller){
        var self = this;
        Ember.run.later(function(){
          self.set('isAnimate', true);
        }, 1000);
    },
});

how can i pass my function to the template in order to dynamically bind the class ?




Serving Ember and Lumen From Cloud 9 Workspace

I'm testing out Cloud 9 and am running into an issue with ports. According to C9 docs ports I can bind to are 8080, 8081 and 8082. I've created a sample Ember app that's being served via ember-cli on port 8080, and when I visit it via <workspace>-<username>.c9.io:8080 everything works fine.

I'm also trying to serve a test Lumen application as an API server for this simple app on port 8081 using php artisan serve --port 8081. Testing API calls via wget on terminal in C9 works, but I can't access the server via <workspace>-<username>.c9.io:8081 and proxying to http://localhost:8081 via .ember-cli config file results in ECONNREFUSED errors.

Do I need to enable or modify something else in my C9 workspace to run this properly in a single workspace?




Variable ember-cli asset fingerprint prepend value

I am trying to setup a cdn url in ember-cli, however I want the actual url to vary between environments.

// ember-cli-build.js

 var app = new EmberApp({
   fingerprint: {
     prepend: 'http://ift.tt/1Jx8YNI' // want this to be variable between envs
     // prepend: 'https://' + process.env.ASSET_HOST + '/' <- this is what I want
   }
 });

I tried adding an environment variable to process.env, but that doesn't appear to exist the way it does if I were to access it on config/environment.js.

Is there a way to have a variable like this in my ember-cli-build.js file?




Ember.js action not firing in FireFox

I am using a SearchBar component where this issue is specifically happening.

<div class="resultRow list-group-item" {{action 'didClickResultDefault' this}}>
...
</div>

This, of course, fires the didClickResultDefault action in my componentcontroller.

On Chrome and Safari (and even IE) this action fires fine. However, specifically on FireFox, when I click to select this element, the action does not fire.

I have tried:

{{action 'didClickResultDefault' this on="click"}}>

but this does not help.

On pc, clicking the element just does not fire the action. On Macs, taps very unpredictably fire the action but a click does not fire the action at all.

What do I change to make Firefox interpret clicking this element to fire the action associated with it??




Calling Ember.set() on property does not notify observer in wrapped component

This is a simplified example but demonstrates my problem well. I have an input for a PIN with buttons for digits (1, 2, 3, 4). The action on my buttons should set a property pinValue which is passed into the wrapped component pin-input. So this is what my code looks like:

See example: http://ift.tt/1MU5sK5

pin-entry.hbs

{{pin-input pinValue=pinValue}}
{{#each numbers as |num|}}
    <button {{action "addNumber" num}}>{{num}}</button>
{{/each}}

pin-entry.js

pinValue: null,
numbers: [1, 2, 3, 4],
actions: {
    addNumber: function (number) {
        this.set('pinValue', number);
        this.notifyPropertyChange('pinValue');
    }
}

pin-input.hbs

<input type=text value={{value}}>

pin-input.js

value: null,
pinValue: null,

onInsertAddObserver: function() {
    // trying to manually subscribe to pinValue here.
    // * from stackOverflow answer
    var controller = this.get('targetObject');
    controller.addObserver('pinValue', this, this.onDataChange)
}.on('didInsertElement'),

onDidChangeInput: function() {
    var current = this.$('input').val();
    this.set('value', current + this.get('pinValue'));
}.observes('pinValue')

The problem is when trying to input duplicate numbers back to back (e.g. 1233 will stop at 123). I cannot seem to force a property change so that onDidChangeInput will fire. The addObserver method is from another post*.

*Some ideas taken from here but did not help me: EmberJS notifyPropertyChange not making it to observer?




Ember-cli project testing with Compass includes css conflicts

I have an ember-cli generated project that uses Compass and the SASS version of Bootstrap. In my app.scss, I have the following imports (for Bootstrap):

@import "../../bower_components/bootstrap-sass/assets/stylesheets/bootstrap";

@import "../../bower_components/bootstrap-sass/assets/stylesheets/bootstrap/theme";


body {
  padding-top: 70px;
  padding-bottom: 30px;
}

When I execute the tests in a browers, the output from the tests are grayed as if there were a modal dialog open. The reason is because the test output page is including app.scss which in turns loads bootstrap and my custom changes. The output looks like this: Notice the 70px padding at the top and that everything is gray

I'm new to Ember testing, so I'm wondering if I am setting up app.scss wrong. Is there a way to have testing work properly and ignore the app.scss styles?




ember-rails Ember Inspector does not detect app

I'm using rails 4 with:

gem 'ember-rails'
gem 'ember-source', '2.0'

ember-rails is at version 0.19 in my Gemfile.lock. I'm very new to ember (and javascript frameworks in general) and I'm following this tutorial. It was written in April 2014 so I think it might be out of date but it's the most recent guide to ember-rails with rails 4 that I can find.

Most of the setup was generated by running rails generate ember:bootstrap and application.js.coffee looks like this:

#= require jquery
#= require jquery_ujs
#= require ember
#= require ember-data
#= require active-model-adapter
#= require_self
#= require api

# for more details see: http://ift.tt/XTBcuN
window.Api = Ember.Application.create()

Also api.js.coffee looks like this:

#= require_tree ./adapters
#= require_tree ./mixins
#= require_tree ./models
#= require_tree ./controllers
#= require_tree ./views
#= require_tree ./helpers
#= require_tree ./components
#= require_tree ./templates
#= require_tree ./routes
#= require ./router
#= require_self

My problem is that when I click on the ember inspector in Chrome's developer tools, I get the 'Ember application not detected' message. The two coffeescript files I referenced above are the only two files the tutorial has talked about so far so I think the error might be with one of them. If you need more information please let me know. When I run the rails server then try to access the Ember Inspector this is what I see in the console:

DEBUG: -------------------------------

DEBUG: Ember : 2.0.0

DEBUG: Ember Data : 2.1.0

DEBUG: jQuery : 1.11.3

DEBUG: -------------------------------

Uncaught TypeError: this.validateFullName is not a function

Ember Inspector Active




How hide a block for a route in ember when go to a sub-route

I'm using Ember 2 and the things for Ember beginners is a pretty confuse. I've the following routes.

queries\

queries\booking

And I my router.js is

this.route('queries', function() {
    this.route('booking');
}

The queries template have some informations, and booking template is more complex. When user go to booking template I want hide some parts from queries template.

How I do this in Ember 2.0 or how I can access in a helper the route to do this?




filter kind of functionality in Ember

Does Ember have filter kind of functionality ?

I want to filter the following like it is done in DOJO below;

var goodData = dojo.filter(overallData, function(individualData) {
    return !dojo.some(rejectedIds, function(rejId) {
        return rejId == individualData.Id;
    });
});




Adding WrapBootstrap Theme to Ember (2.0)

I've installed ember-cli-less and I have included

@import "../../bower_components/bootstrap/less/bootstrap"

In the my styles/app.less file

I have the following in ember-cli-build.js file:

app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot', {
    destDir: 'fonts'
  });
  app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf', {
    destDir: 'fonts'
  });
  app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg', {
    destDir: 'fonts'
  });
  app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
    destDir: 'fonts'
  });
  app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', {
    destDir: 'fonts'
  });

  app.import('bower_components/bootstrap/dist/js/bootstrap.js');

  return app.toTree();

Now I want to take a theme from Wrapbootstrap and include it in my project.

There is another link to a similiar question: Recommended way to include bootstrap library in Ember.JS ember-cli App however - it seems to concentrate mostly on just getting bootstrap setup - it doesn't go much into adding a theme.




Send actions to parent component?

I've a template like this:

{{#the-table}}
   {{#the-row selectedRow=selectedRow selectRow="selectRow"}}
     <td>something</td>
   {{/the-row}}
{{/the-table}}

When I click on the-row, an action (selectRow) is fired.
I would expect the-table to receive the action, but instead it's the parent view/component the receiver.

How can I change this behavior?




Accessing an object property with a non-standard name in HTMLBars template

{{my-component can-delete=true canDelete=true}}

In the my-component template I want to access can-delete from the attrs object.

{{attrs.can-delete}} <!-- does not work, prints blank, should print true -->
{{attrs.canDelete}} <!-- works, prints true-->

How can I access object properties from HTMLBars that are not in the usual format?




EmberJS route design for multi-step workflow

I am trying to understand the best way to design a multi-step workflow;

So I have the following possibilities;

Step 1 (list) > Step 2a (review screen a) > Step3 (confirm screen)

Step 1 (list) > Step 2b (review screen b) > Step3 (confirm screen)

At each step, I call an API and based on the response, I make a decision. It is possible that user moves from Step 1 directly to Step 3 (based on API response)

OR it is also possible to have

Step 1 (list) > Step 2a (review screen a) > Step 2b (review screen b) > Step3 (confirm screen)

What is the best way to design the routes considering the above ? I mean in terms of nested routes, dynamic segments, folder structure for route objects, etc ?




mardi 27 octobre 2015

How to get a list of all ember-data Model classes?

Individual models can be fetched with store.findRecord(modelTypeName, id);; how can I get a list of all the possible modelTypeNames available in my app?

I'm using ember-cli version 1.13.8 with Ember 2.1.0




emberjs - sorting data retrieved from Firebase

I've spent the last three days trying to figure this out and i hope someone from here could help.

Note regarding setup: I'm working off Ember-Cli therefore my Ember version 1.13.7 and Ember-Data 1.13.8

To learn more about how emberJS works i decided to create a simple blog system that i will use on my own website. The data is loaded from a Firebase database using the Emberfire plugin.

Help: I cannot sort the data i retrieve into a descending order. For example, if i have 5 posts created on Monday, Tues, Wednesday, Thursday and Friday. Each with a unique timestamp in numerical order.

When i retrieve data it shows in this order:

1st ever post (oldest)
2nd ever post
3rd ever post
4th ever post
5th ever post (newest)

i want to reverse the order so my latest blog post appears on top.

I am retrieving data with the following code:

return this.store.find('post');

I can't work out how to use: sortBy which is from Ember itself or the orderBy() which is from firebase/emberfire?

I understand it needs to be inside a controller which will modify the data from the model before presenting it in the view. But can anyone help?

heres some more code:

Attempt at a controller - it doesn't work:

import Ember from 'ember';

 export default Ember.ArrayController.extend({
    sortedModel : function(){
        return this.get('model').sortBy();
    }.property('@each')
});

View Template:

{{#each sortedModel as |post|}}
    {{#blog-post post=post}}{{/blog-post}}
{{/each}}

{{outlet}}




Ember CLi SC is not defined when using css animation

I have a music component in an ember application using SoundCloud API, i have recently added a css animation with Font-awesome. See codepen

This is my markup

<div class="gears">
    <i class="fa fa-cog fa-spin fa-fw small"></i>
    <i class="fa fa-cog fa-counter fa-fw big"></i>
</div>

After that my music component stopped working in chrome and JS hint is giving me a 'SC' is not defined here

    return SC.stream(favoritePath, {
        whileplaying: function() {
            return self.set('currentFavoritePosition', this.position);
        },
        onbufferchange: function() {
            return self.set('isBuffering', this.isBuffering);
        },
        onfinish: function() {
            self.set('isPlaying', false);
            if (self.get('nextFavorite') != null) {
                return self.send('selectFavorite', self.get('nextFavorite'), index);
            }
            self.set('favorite.artwork_url', nextFavorite.artwork_url);
        }

In Safari and Firefox there is no problem, the music component is working.

I read that there is an issue about troubles of identifying this kind of global objects by JSHint, but i don't know if there is a connection with my case and why this happened after this animation and only in Chrome




How to translate controller member arrays in Ember-i18n?

In my customer controller I have defined some constant arrays that are used for populating select input (dropdown) options.

import Ember from 'ember';

export default Ember.Controller.extend({
    occupations: [
        {code: 'student', name: "Student"},
        {code: 'worker', name: "Worker"},
        {code: 'retired', name: "Retired"},
        {code: 'other', name: "Other"}
    ]
});

Normal solution would be using translationMacro function t() or this.get('i18n').t() around translation key, but they can't be used in such situation as "this" inside object or array will not refer to controller.

What is best practice for solving such situation?




Ember.js Asynchronous Object Parameter

I am having some issues with Ember.js and loading resources asynchronously (aka I don't know what I'm doing). This is what I have. It currently doesn't update the list parameter after receiving the data. The template does not render anything. Thanks for any help.

Utilities

import Ember from 'ember';

export var page = Ember.Object.extend({
  type: null,

  list: Ember.computed('type', function() {
    var type = this.get('type');
    var url = "/test/" + type + "/test2";

    if (type) {
      getArray(url).then(function(list) {
        return list;
      });
    } else {
      return [];
    }
  })
});

export function get(url) {
  return Ember.$.ajax({
    url: url,
    type: 'GET',
        dataType: 'text',
        cache: true,
    xhrFields: {
         withCredentials: true
    }
  });
}

export function getArray(url) {
  return get(url).then(
    function(file) {
      var array = file.split("\n");
      array.pop();
      return array;
    },
    function() {
      return ["Error!"];
    }
  );
}

Route

import util from 'app/utils/utilities';

export default Ember.Route.extend({
  model(params) {
    var p = util.page.create({
      type: params.log_type
    });

    return p;
  }
});

Template

{{#each model.list as |item|}}
  <li><a href="{{item}}">{{item}}</a></li>
{{/each}}




responding to an internal server error with ember-data

I'm using ember-data 2.1.0. What is the recommended approach to handling 500 status code requests.

I'm using the RESTAdapter and when I attempt to update a model and the server responds with a 500, the model's isError flag is set to true but the errors don't get assigned to the model.

Is there someplace globally I can define what should happen? I would like the errors to still be attached to the model as they are when the server responds with a 400.




Ember.js Route: How to avoid infinite loop when refreshing parent route from child setupController

I have two nested routes, projects and projects/project. Whenever I open a project, I would like the projects route to be refreshed.

What I am doing know is to call a controller function during the setupController hook (that will end up calling refresh in the projects route). Something like this:

  // project route
  setupController: function(controller, model) {
    this.controllerFor('projects').send('search');
    controller.set('model', model)
  }

  // projects controller
  actions: {
    search: function() {
      // do other things
      this.send('refreshModel');

    }
  }

  // projects route
  actions: {
    refreshModel: function() {
      this.refresh();
    }
  }

The problem is that, when the refresh function is called, it not only refreshes the current route, but also all the children routes, meaning that this setupController hook will be executed again, creating this infinite loop.

Is there a way to make Ember refresh just the current route, ignoring its children?

Thank you.




How to add condition to EmberJS Input Helper

How can I build a this input <input class="{{unless isEditing "hidden"}}" /> with the input helper of Ember.js?




How do I access Ember.js API documentation?

I'm using an older version of Ember (two older versions in fact) and I'd like to view the API docs for a version that's older than 2.x, the versions I'm using are Ember v1.12.0 and v1.10.0.

I already know how to access the older guides using the dropdown menu but there's no menu like that for the API docs.

Is there a way to get this online or can I generate the API docs locally for my particular versions of Ember?




EmberJS and third-party libraries

I'm trying to implement digest auth in Ember app. To complete this I took this library - http://ift.tt/1BAWLVl. But I have no idea how to use it in an app. Now my auth service looks next:

import Ember from 'ember';

export default Ember.Service.extend({
    path: "some-path",
    username: "",
    password: "",

    me(successHandler) {
        var meRequest = new digestAuthRequest('GET', this.path + "/me", this.username, this.password);
        meRequest.request(successHandler);
    },

    setCredentials(username, password) {
        this.username = username;
        this.password = password;
        console.log(this.username);
    }
});

And I got following errors:

services/auth.js: line 9, col 29, A constructor name should start with an uppercase letter.
services/auth.js: line 9, col 29, 'digestAuthRequest' is not defined.

My only attempt was adding digestAuthRequest.js to vendor folder, and adding

app.import('vendor/digestAuthRequest.js');

to ember-cli-build.js.

Looks like it's completely incorrect. So what I need to do to use such library in Ember app?

P.S. EmberJS version - 1.13.




Using Breez.js with Ember.js

This is more of an exploration question. We have been using breeze.js in our projects for a while and have been quite satisfied with it; it ties nicely into concepts we already know and use (change tracking, metadata, backend agnostic...)

Now we are evaluating the possibility to move our front-end from backbone/marionette/knockout stack to ember.js (which seems to be more of a complete framework than a "pick-only-what-you-need" approach in backbone). We are exploring to possibility to keep using breeze.js as our data management layer on the client-front.

But how can the integration of models returned from the server (server stack: node.js + mongoDB) be done with models defined by ember.js?

A typical ember model definition could be:

Person = Ember.Object.extend({
             Property1: 'lala',
             Property2: 'bbb'
});

where you can see the extension "Ember.Object.extend"

Breeze.js upon receiving data from server attach a AspectEntity to them (and if Knockout is defined, wrap properties in observables ). How could returned objects somehow be "transformed" into ember.js objects?

Maybe the way we approach this problem and the way we think about this integration is totally wrong or that we should entirely reject this "ember-breeze" combo. From google search we have not found cases where breeze is used with ember.js or some guidance. That is why we come to the stackoverflow community: is it possible? what are the possible pitfalls to look ahead?




Use Ember compare helper (version 1.13)

I want to use the below helper

{{compare model.someCount 0 operator = ">"}}

How can I use it? I am getting error "Assertion Failed: Helpers may not be used in the block form, for example {{#my-helper}}{{/my-helper}}. Please use a component, or alternatively use the helper in combination with a built-in Ember helper, for example {{#if (my-helper)}}{{/if}}."

My helper looks as below;

import Ember from 'ember';

export function compare(lvalue, rvalue, options) {
    if (arguments.length < 3)
      throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
    operator = options.hash.operator || "==";
    var operators = {
      '==': function (l, r) {
        return l == r;
      },
      '===': function (l, r) {
        return l === r;
      },
      '!=': function (l, r) {
        return l != r;
      },
      '<': function (l, r) {
        return l < r;
      },
      '>': function (l, r) {
        return l > r;
      },
      '<=': function (l, r) {
        return l <= r;
      },
      '>=': function (l, r) {
        return l >= r;
      },
      'typeof': function (l, r) {
        return typeof l == r;
      }
    }
    if (!operators[operator])
      throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator);
    var result = operators[operator](lvalue, rvalue);
    if (result) {
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
}

export default Ember.Helper.helper(compare);




Use Handlebars in EmberJS

I am trying to use a custom helper in my Ember project. So I have done bower install --save handlebars

and then under helpers\compare.js, I have

import Handlebars from 'handlebars';

Handlebars.registerHelper('compare', function (lvalue, rvalue, options) {
}

Is this the correct way to import Handlebars js and use it inside helper ?




Create Custom Emberjs Service Error: Attempting to inject an unknown injection: `service:titleService`

I hit the above Error: Attempting to inject an unknown injection: service:titleService with the following code:

// initializers/titleService
export default {
  name: 'titleService',
  initialize: function(container, application) {
    application.inject('route', 'titleService', 'service:titleService');
  }
};

// services/titleService.js
import Ember from 'ember';
export default Ember.Service.extend({
  title(name) {
    this.set('title', name);
  }
});

// routes/login.js
import Ember from 'ember';
export default Ember.Route.extend({
  titleService: Ember.inject.service(),
  actions: {
    didTransition: function() {
      this.set('titleService.title', 'Login Page');
    }
  }
});

// templates/application.hbs
<div class="page-header">
   <h1>{{titleService.title}}</h1>
</div>
{{outlet}}

am I missing anything?




Using simple auth without Ember-cli

I want to use simple auth without Ember-cli. Up until version 0.8.0, simple auth was distributed as a bower addon, and could be imported with the AMD module inside the bower package (ember-simple-auth/simple-auth.amd.js). Since I want to use the newest version of Ember and Ember Data, I also need to update the simple auth version to version 1.0.1.

How do I use the new version without Ember-cli?




Can not send same action from different components

I have two components which should send action to controller, but only one of them does work

My controller:

`import Ember from "ember"`

CourseIndexController = Ember.ObjectController.extend
  actions:
    openStep: (unit, step, routeName)->
        @transitionToRoute(routeName, unit, {queryParams: {scope: step}})
`export default CourseIndexController`

And my components:

UnitTableStateComponent = Ember.Component.extend  
  step: ''
  unit: ''

  openStep:( ->
    @sendAction('action', @get('unit.id'), @get('step'), 'unit')

  ).on('click') //it works
`export default UnitTableStateComponent;`


ExamTableStateComponent = Ember.Component.extend
  exam: ''
  step: ''
  openStep:( ->
    @sendAction('action', @get('exam.id'), @get('step'), 'exam')

  ).on('click') //id does not works
`export default ExamTableStateComponent;`

I can not understand what's wrong with ExamTabeStateComponent or with whole my code

ember version: 1.13.8




Handle conditions in Handlebars template

I am using Ember with Handlebars template

How can I get the following support in Handlebars ?

{{#if response.someCount> 0}}

Would I have to add some mapping attribute in Controller to achieve this ?




lundi 26 octobre 2015

ember cli sass ENOTDIR: not a directory, scandir

I'm trying to use ember cli with sass, so i installed the ember-cli-sass, and i'm trying to configure like this:

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

var emberCLIBuild = function(defaults) {
  var app = new EmberApp(defaults, {
    sassOptions: {
      includePaths: [
        'app/styles/admin/main.scss',
        'app/styles/site/main.scss'
      ]
    }
  });

  return app.toTree();
};

module.exports = emberCLIBuild;

but, when i try to run ember serve, the terminal will throw an error:

ENOTDIR: not a directory, scandir '/Users/celicoo/DEV/PubCrawl/Site/tmp/sass_compiler-input_base_path-55sPHD0L.tmp/1/'

How could i fix this? I don't see the problem.

Thanks.




How to display JSON data from a rails API to ember.js view

I have a rails API that when I load a particular route it returns a JSON response to my browser. The URL I put in my browser is http://localhost:3000/api/csv_files

And the output looks like the following, API output

Now I want to load this output / csv_files using ember.js but I am not entirely sure how this would work?

I included ember-rails gem in my rails app, and I have the appropriate files loaded in the rails app, but I am not sure how I could connect an ember template to the rails API controller to display the output.




Ember: Setting variable in template from controller

I have a variable in my template called someString that I would like to set in my controller. I am getting a Uncaught Error: Assertion Failed: TypeError: Cannot read property 'set' of undefined.

How do I make the controller aware of the template variable(if that even is the solution to this problem)?

My template looks like this:

{{#modal-dialog action="close" title="New Run"}}
  <form role="form" {{action "submit" on="submit"}}>
...
  {{input value=emailComparisonRunID class="form-control" placeholder="Comparison Run ID (optional)"}}
  <label><small>{{someString}}</small></label>
  <br>
...
  </form>
{{/modal-dialog}}

My controller looks like this:

export default Ember.ObjectController.extend({
  needs: 'services',
  dataVer: '',

  watchEmailComparisonRunId: function() {
    var comparisonId = this.get('emailComparisonRunID');
    if(comparisonId == null) {
      comparisonId = 1;
    }

    var onIdFound = function(id) {
      console.log('FOUND');
      this.set('someString', 'FOUND');
    };

    var onIdNotFound = function(reason) {
      console.log('Not Found');
      this.set('someString', 'NOT FOUND')
    };

    this.get('store').find('run', comparisonId).then(onIdFound, onIdNotFound);

  }.observes('emailComparisonRunID'),
  
  ...

  
  



How to pass multiple values from view to controller trough an action in Ember.js?

I have the following text input

<input type="text" name="item-name" value={{item.name}} onblur={{action "confirmName" value="target.value"}} />

How can I pass not only target.value but also the related item to confirmName?




How to declare "escape-press" into HTML like Ember.js templates?

How to write "escape-press" action in a more HTML format than {{input escape-press='alertUser'}}.

I have some inputs defined like that <input type="text" name="item-name" value={{item.name}} onblur={{action "confirmName" value="target.value"}} /> and I would like to keep this syntax.




Ember model not populating template

I'm attempting to grab some data from my rails api and display it in the template. I'm very new to ember so the simpler the explanation the better and forgive me if this is a very stupid question. Any help would be greatly appreciated, I've been trying to get this working for hours.

Here is my template in jobs.hbs

{{#each job in model}}
   <a href={{title}}>
      <div class="info">
          <div class="title">{{body}}</div>
      </div>
   </a>
 {{/each}}

My route in routes/external/jobs.js

import Ember from 'ember';

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

My Jobs model in models/jobs.js

import DS from 'ember-data';

    export default DS.Model.extend({
    jobs: DS.hasMany('job')

});

My job model in models/job.js

import DS from 'ember-data';

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

My adapter in adapters/jobs.js

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({
   primaryKey: '/jobs'
});

I am expecting my api to return data in the form

{
  "jobs": [
      {
        id: "jfdsa132113",
        title: "developer",
        type: "Job",
        body: "lorem ipsum",
        tags: [
              "some stuff",
              "more stuff"
        ]
      },
      {
        id: "jfdsa132113",
        title: "developer",
        type: "Job",
        body: "lorem ipsum",
        tags: [
              "some stuff",
              "more stuff"
        ]
      }
   ]
}




How do I convert these initializers to instance initializers when upgrading from ember.js 1.11.3 to 1.12 to remove the deprecation warnings?

I'm in the process of upgrading our ember/ember-cli version from 1.11.3 to 1.12, in prep for hitting 1.13 and 2.0 soon after.

However, I'm having some trouble deciphering exactly what has changed wrt initializers and instance-initializers... have looked over the docs and read quite a lot of posts, but still not clear on how these work. I'm particularly confused about the difference between application.register and container.register, and when I should be using application, container, or instance.

Going from ember.js 1.11.3 to ember.js 1.12, ember-cli 0.2.2 to ember-cli 0.2.7

My initializers are fairly simple, can someone help me convert them? A brief overview or link to such on how exactly ember works during the initialization / instance-initialization process would also be helpful.

Here are my existing initializers from 1.11.3:

initializers/auth.js

import Ember from 'ember';
import Session from 'simple-auth/session';
import CustomAuthenticator from 'soxhub-client/authenticators/soxhub';
import CustomAuthorizer from 'soxhub-client/authenticators/soxhub';

export default {
  name: 'authentication',
  before: 'simple-auth',

  initialize: function(container, application) {
    Session.reopen({
        user: function() {
            var userId = this.get('user_id');
            if (!Ember.isEmpty(userId)) {
              return container.lookup('store:application').find('user', userId);
            }
        }.property('accountId')
    });

    console.log('registering authenticator on container');
    container.register('authenticator:soxhub', CustomAuthenticator);
    container.register('authorizer:soxhub', CustomAuthorizer);
  }
};

initializers/inject-session-into-service.js

    import Ember from 'ember';

    export default {
        name: 'inject-session-into-service',
        after: 'simple-auth',

        initialize: function(container, application) {
            console.log('ran initializer for sesion');
            application.inject('service:pusher', 'session', 'simple-auth-session:main');
        }
    };

initializers/inject-store-into-component.js

export default {
  name: "injectStoreIntoComponent",
  after: "store",

  initialize: function(container, application) {
    console.log('injecting store onto component');
    // container.typeInjection('component', 'store', 'store:main');
    application.inject('component', 'store', 'store:application');
  }
};




Ember app renders blank page when typing in a specific URL

In my Ember app, if I'm developing locally I can directly go to a page by going to the url http://localhost:4200/some/page. I can also navigate to that page within the app itself.

However, after my app is deployed and I go to https://dev.myapp.com I am able to navigate around the site just fine but if I try to go to a url directly (such as http://ift.tt/1GEGSQD) there is nothing rendered in the browser and the DOM is completely empty. But if I enter https://dev.myapp.com/ back into the browser I am able to start navigating the app again.

Would this have to do with how I build or deploy my app or is this something that I might have configured wrong within the Ember app itself?




Ember Data and Handsontable recursion

When a Handsontable is instantiated, it calls a recursive method to build a data schema: http://ift.tt/1PQpjiE, which in turns calls objectEach: http://ift.tt/1LSuAB4

However, with an Ember Data record, it tries to iterate over properties like store, which means it gets caught in an endless loop.

Is there any way to bypass the recursiveDuckSchema method?




Radio buttons in ember 2.0

So its been a month with ember right now, im really happy with it but getting information is kind of hard due to the amount of versions there is and how they change stuff between versions.

Regarding build in input elements i have found the following

for text type fields
{{input class='input' type='email' value=email}} 

{{textarea value=pictureDescription class='textarea' id='coolTextArea' value=content}}

{{input type="checkbox"  checked=model.allowComments}}

{{input type="file"  name="image"  value=image class='hidden_file'  }}

even cool selects

{{view "select"
                            content=languagePreferences
                            optionValuePath="content.code"
                            optionLabelPath="content.label"
                            class="my-dropdown" value=model.submisionType}}

which was kind of confusing since i read in older versions selects were kind of complicated.

Whats the deal with radio buttons? Are there native radio buttons ? or should i use something like :

http://ift.tt/1GEwqsp

i dont want to use strange dependencies (as i used to with x-select) when there are native available

Thanks in advance




Ember simple auth add token as query parameter in custom authorizer

How I can do to make the authorizer add the token as a query parameter in my requests to the server?

For example I have a GET to: http://domain/api/resource

And I want the authorizer add the token: http://domain/api/resource?token=TOKEN_DATA




Using Ember without Ember CLI

I'm starting using Ember, but i don't like this ember cli, so i want use it without. Is this wrong? Should i stick with Ember CLI?

I don't agree with this bundle generation stuff, plus i agree 100% with this guys -> http://ift.tt/1ORH2qu

I love to create my own stuff, but i'm feeling that i'm swimming against the tide, i know?

Ember team will force people to use ember cli? Because if they are, i'm going to suffer to change the application later.

There are big projects using ember without the cli?

Thanks.




How to toggle class in Ember

I'm trying to figure out how I can toggle a class in a component.

I have my component that has two states: active and desactive. When I want to active it, I need add the class active.

Currently I'm using jQuery addClass and removeClass.

Component.js:

SiteApp.BookingBoxComponent = Ember.Component.extend({
      actions: {
        open: function (element) {
          this.sendAction('open', this.$());
        },

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

Controller.js:

SiteApp.IndexController = Ember.Controller.extend({
  actions: {
    open: function (element) {
      element.addClass('event--active');
    },

    close: function (element) {
      element.removeClass('event--active');
    },
  }
});

It is working, but I have this feeling that Ember has something build in that will help with this.




How to call an action on the app route from any component without having to pass it everywhere?

I'd like to be able to open a login modal from any component without having to pass it through the component hierarchy each time I need it.

The openModal action on the application is the same as in the modal cookbook in the guides :

App.ApplicationRoute = Ember.Route.extend({
  actions: {
    openModal: function(modalName) {
      return this.render(modalName, {
        into: 'application',
        outlet: 'modal'
      });
    }
  }
});

I would like to avoid :

{{my-component openModal="openModal" otherArgs=args ... }}

Plus import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    openModal(modalName) {
      this.sendAction('openModal', modalName);
    }
  }
});

I could use a service injected in each component, but then how to call the openModal action on the application route from the service ?

Thanks !




How to propagate changes from actions to template instantaneously Ember

My ember action is taking a lot of time and I am trying to show user something while the control is inside the action,

My ember controller is :

.. = {
    isLoading : false,
    actions : {
        create : {
            this.set('isLoading', true);
            // do some stuff...
            this.set('isLoading', false);
        },
    },
}

And the template is

the value of isLoading is {{isLoading}}
<div {{action "create"}} >Go!</div>

But when I click on Go, the value of isLoading does not change.




dimanche 25 octobre 2015

Unhappy with the code itself and how codes are littered

this post is yet another outburst, hoping to find someone like me who are unhappy with codes are itself.

I'm a JS developer, I work alone in my three years career. I learned paying courses in frontendmasters, treehouse, codeschool, lynda, etc .. I never had an exchange of experiences with anyone.

A few months ago, I've become increasingly critical of my own code, refactoring once after another .. when I finish I think is good, but it's just spend 3 days I think there's something wrong and there goes again ... refactoring.

I can't let go, just to see the working code and go to the next, it has to be beautiful as well, an example would be:

this:

$ ('button'). On ('click', function () {
 $ (this) .hide ();
});

becomes this:

var Toggle = {
 init: function () {
   var button = $('button');

   button.bind('click', this.toggle);
 },

 toggle: function () {
  $(this).hide();
 }
};

Everything needs to be aligned .. well, Its looks like I have OCD.

I search libraries like ember, jquery, etc and i thinkg the source code is horrible..

As you can see, I have a problem. I loved program, never had those problems before and do not know how I was getting in this state.

I would like to ask for help, what could I do to overcome this?? Someone goes through it? I often see stupid codes that could be written in a better way, but just are not ... why is that? I'm freaking out?




Ember data, how to get max id for store

need your help. Is there a way to query the ember data store to find the max id for a given model? I know I could find all, walk through the objects, store ids when they are greater than the previous, etc, etc.

I'm new to Ember, I'm used to being able to call aggregate methods on database, you know, max(), min(), sum() all that stuff. There HAS to be a way to do this in ember, right? I have searched and searched, I'm honestly a little mystified that I can't find anything for what has to be a very common use-case.

I'm currently using fixtures, want to add a new line to an order. When I create the new record I need to find the max id of all other records so I can increment it for the new record.




Possible to make a route transition inside of a service in Ember?

I'm using ember-cli 1.13.8 and I have a service that handles most of my logic. Right now I have a function that listens to whether certain things are true or false and then can make a route change based upon that. I'd rather not have to call that function from inside every route since I want it to happen on every route. Its goal is to determine whether the player won and every interaction in the game drives this.

Inside of my game service:

init() {
  ... 
  if(true) {
    console.log("you've won!");
    this.transitionTo("congratulations");
  }
},

Of course, this fails because this isn't a route like Ember expects. I know I can call this method from inside of every route instead but I'm wondering if there is a better way to do this.

Thanks

Edit

So far I've tried importing in the App and then trying to extend the Router. This seems like a bad idea though.




Updating component display from route

To learn more about using services and components, I'm trying to set up a simple flash-message style service. Within my route, I'm saving a record and receiving either a json notice or json error from the server.

Since this is a behavior I'd eventually like to use app-wide, I'm using a simple service (injected into my routes) to handle displaying the message. Within a route, I'm able to call this.get('notification').displayMessage(msg).

Currently the displayMessage function within the service is just alerting the message because I'm stuck on how to create a component that the service can "update". How can a service communicate with a component so that I can send a message and display it from the component template?

profile/index route

user.save().then( (response) => {
  //display response.notice in the app-notification component template
}, (response) => {
  let errors = JSON.parse(response.errors);
  //display response.error in the app-notification component template
  this.get('notification').displayMessage(errors[0]);
}

service

import Ember from 'ember';

const { Service } = Ember;

export default Service.extend({

  displayMessage(msg) {
    alert("message ---> " + msg);
  }
});

component

???

component template

<h2 class="alert">{{message}}</h2>

application template

{{app-notification message=message}}




How to work with nested routes in Ember.js

I'm new to Ember.js and I stuck with nested routes and I need help.

This is what I want to achieve:

enter image description here

I think this is called Master-Detail page.

more systematically it looks something like this:

enter image description here

UsersIndexRoute displays list of people. UsersShowRoute displays information for particular person.

Here is my routes:

Router.map(function() {
  this.route('users', { path: '/users'}, function() {
    this.route('index', { path: ''}, function() {
      this.route('show', { path: '/:id' });
    });
  });
});

enter image description here

UserIndex Template looks like this:

{{#each item in model}}
  {{#link-to 'users.index.show' item.id}} {{item.firstName}} {{item.lastName}}{{/link-to}}
{{/each}}

When I try URL like 'http://localhost:4200/users/1' for example, according to debugger I am be able to reach controller 'users.index.show' (the desired one)

enter image description here

The route for UserShowRoute looks like this:

export default Ember.Route.extend({
  renderTemplate: function() {
    this.render({
      outlet: 'detail'
    });
  },
  model: function(params) {
    return this.store.find('user', params.id);
  } 
});

I am using ember-cli 1.13.8

I hope my explanation makes some sense to you. Thanks in advance.




Dynamic navigation bar in ember.js with different routes

I'm trying to create a dynamic navigation bar in ember. I have a partial header included in application template which have an element 'search' that should be only visible when I get to my events index route. I have tried to do that this way:

ApplicationController = Ember.Controller.extend(
  eventsIndexController: Ember.inject.controller 'events/index'
  isSearchActive: Ember.computed 'eventsIndexController.showSearch', ->
    @get 'eventsIndexController.showSearch'

And in events index controller:

EventsIndexController = Ember.Controller.extend(
  showSearch: false

When it gets to events index route

EventsIndexRoute = Ember.Route.extend(
  model: ...

  setupController: (controller, model) ->
    controller.set('model', model)
    controller.set('showSearch', true)
  deactivate: ->
    @controllerFor('events.index').set('showSearch', false)

And it works fine - model is set properly and search option is only visible in events index route. The problem is that I would like to perform some action when search is clicked but since this action is declared in EventsIndexController I can't call it in normal way from application template. So my first question is:

  • do you know how to achieve that?

And second question is:

  • how can I accomplish what I'm trying to do in better way because it doesn't seem to be very clear way and it might get really complicated in a course of time when I'll need new dynamic segments.



I have tried to call a data through JSON using EMBER . But it's not coming properly

          //21_JSONcall.html 
          <!DOCTYPE html>
            <html>
            <head>
              <meta charset="utf-8">
              <title>Ember Starter Kit</title>
              <link rel="stylesheet" href="css/normalize.css">
              <link rel="stylesheet" href="css/style.css">
            </head>
            <body>
              <script type="text/x-handlebars"> 
                <h2>Welcome to Ember Table</h2>
            <h2>Definig Models</h2>
            {{outlet}}
              </script>

            <script type="text/x-handlebars" id="index">
            <ul>
                {{#each item in model}}
                  <li>{{item.name}} :{{item.designation}} : {{item.salary}} :{{item.joining_date}} :{{item.office}} :{{item.extension}}</li>

                {{/each}}

             </ul>    
            </script>



    //sids.json
    {  
       "sids":[  
          {  
             "id": 1,
             "name":"Honey jain",
             "designation":"Software Engineer",
             "salary":"$1000",
             "joining_date":"2015/05/15",
             "office":"Mumbai",
             "extension":"5051"
          },
          {  
          "id": 2,
             "name":"Saurabh jain",
             "designation":"Software Engineer",
             "salary":"$1001",
             "joining_date":"2015/05/15",
             "office":"Mumbai",
             "extension":"5052"
          },
          {  
          "id": 3,
             "name":"Yash jain",
             "designation":"Software Engineer",
             "salary":"$1002",
             "joining_date":"2015/05/15",
             "office":"Mumbai",
             "extension":"5053"
          }

       ]
    }


    //21_JSONcall.js

    App = Ember.Application.create();



    App.SidAdapter=DS.RESTAdapter.extend({

        namespace: "embertest/json", 

            suffix: '.json',

          pathForType: function(type) {
            return this._super(type) + this.get('suffix');
          },


    });


    App.Sid =DS.Model.extend({
        name: DS.attr('string'),
        designation: DS.attr('string'),
        salary: DS.attr('string'),
        joining_date: DS.attr('string'),
        office: DS.attr('string'),
        extension: DS.attr('string')

    });


    App.IndexRoute = Ember.Route.extend({
          model: function() {

            return this.store.find('sid');
          }
    });

//My required output is in form of table but i'm not able to get the output properly . Console is not showing anytype of error . Please help if i have done anything wrong while writing this code . I'm new to emberjs. Thanks

//OUTPUT :

Welcome to Ember.js
Definig Models

    Honey jain
    Saurabh jain
    Yash jain




samedi 24 octobre 2015

how to get the global Ember.Application instance in phantomjs?

The application also uses requirejs, so App was not defined in global scope, i.e. can't be referred to as window.App.




How to upgrade push and pushMany use from Ember 1.13.x to 2.x?

I'm trying to update from 1.13.x to 2.x and deprecated update all calls to push and pushMany. But with synchronous relationships, I get the error

"Uncaught Error: Assertion Failed: You looked up the 'profile' relationship on a 'tenant' with id 2 but some of the associated records were not loaded."

I'm not understanding this error because the relationship for profile is side-loaded. Here's my json output.

My relationship looks like this...

profile: DS.belongsTo('profile', { async: false })

and I'm loading data in like so...

let tenantData = store.normalize('tenant', response.tenant);
let tenant = store.push(tenantData);

Works great if I set the async to "true" but I don't want to make another call to the API since I already have the data in the main ajax call.




Ember naming for parent/child objects

I am trying to understand how naming works for parent/child objects in EmberJS.

Say I have 2 controllers as below;

// controllers/flash-messages.js
// controllers/posts/view.js

Now if I want to access "flash-messages" controller inside my "view" controller, I can just write the below in my controllers/posts/view.js

needs: ['flash-message'],

However, now assume I have one more controller as below (in sub-folder)

// controllers/posts/flash-messages.js

Now how do I distinguish between the 2 "flash-messages" controller ? Is there any way by which I can refer to each of them uniquely ?

Also does the same concept apply to models & routes ?




Dynamic segment is not working in ember

I'm trying to have this kind of a route in my project where the last part is user ID. http://localhost:4200/profile/5621140ff60f6dee985b88aa

I need to display details of user that have the above ID only.But after creating following files i found that all the users are loaded to template. not only the user that have specific Id. Why is that??

router.js

Router.map(function() {

  this.resource('profile', { path: '/profile/:user_id' });

   });

route/profile.js

import Ember from 'ember';

export default Ember.Route.extend({

    model: function(params, transition) {

        return this.store.query("user", params.user_id);
    }

});

profile.hbs

<h2>Welcome user</h2>

{{#each item in model}}
{{item.firstName}}
{{/each}}

server.js

app.get('/api/profile', function(req,res) {
    UserModel.find({},function(err,docs) {
        if(err) {
            res.send({error:err});
        }
        else {
            res.send({user:docs});
        }
    });
});




This.get(‘model’).addObjects(records); throw excption “Uncaught TypeError: internalModel.getRecord is not a function”

Friends I need help, afrer updating to ember 2.X, my infinite scroll stopped working. On reaching page end, I query store to get new records

 load_more: function(){
 var self = this;
  this.get("store").query("actor",{pg: 1}}).then(function(records) {

    self.get('model').addObjects(records); // this throw excepton 

  }
}

this was working perfectlly but now self.get('model').addObjects(records); throw excption "Uncaught TypeError: internalModel.getRecord is not a function" in record-array.js at line 86 "return internalModel && internalModel.getRecord()". I tried using self.get('model').pushObjects(records) but it also give same error, please help




Ember With Node and Express User Authentication

I need to develop user login and authentication to my ember.js application my backend runs on Node and Express I have extensively searched and found no good guide on how to implement that it will be a great help if you can explain how exactly the process should be on both Client and server side.

p.s-I need to authenticate users from my mongo database. not 3rd party service provides




Is there a way to implement history.js with angular or ember?

I know they have their own routing and there is for example a tutorial to remove the # here.

I read that the different browsers handle the history api differently and that the history.js is a way how to tackle this issue.

So is there a way how to combine those front-end frameworks with that api? I'd start somewhere in the routing but get stuck thinking about what to do...