lundi 30 novembre 2015

Handlebars RegisterHelper with Ember Error

I'm pretty lost after trying numerous different things. I am building an Ember site and inside of one of my Handlebars templates, I want to display a link only if a condition is true. Here is my template.

<script type="text/x-handlebars" data-template-name="project">
    <div class="project-container">
        {{is_external model.url model.title}}
    </div>
</script>

Now, my registerHelper in my js file:

Handlebars.registerHelper('is_external', function(url, title, options) {
  if (url.indexOf("codepen") < 0) {
      return "<p class='view-external-link'>"+
            "<a href='{{url}}'' aria-label='View {{title}}'' target='_blank'>Visit Site</a>"+
            "</p>";
  }
});

The error I keep receiving however, is: Uncaught TypeError: Cannot read property 'isHelperFactory' of undefined coming from my ember.js file.

Ideally, I would prefer to just return true or false from the helper to keep the Html out of my helper function but first I just need some help getting it working.

I am including ember, ember_compiler, and handlebars on my page as well.




Emberjs link-to href test in integration component

I'm trying to test a link-to href property in an ember component. with ember 2.0 but when I render the component with renter hbs it renders this:

<div id=\"23\" class=\"ember-view\">
<p><!----></p>
<div class=\"participantes\">
    <a id=\"ember282\" class=\"ember-view\">     
        <span>rnt-ayl-bld-js-jvr-frd-edw</span>
    </a>
</div>  

and the href property is not rendered, I read that is something related to router but I'm not sure how to include the router in the test I tried something like:

moduleForComponent('conversation-item', 'Integration | Component | conversation item', {
integration: true,
setup(){
    const router = this.lookup('router:main');
    router.startRouting(true);
}

});

but the lookup function is not present

TypeError: 'undefined' is not a function (evaluating 'container.lookup('router:main')')




Ember-Simple-Auth and Torii

I am having a problem in connecting ember-simple-auth and torii in order to do a facebook authentication.

I have in my config/environment.js:

torii: {
  providers: {
    'facebook-oauth2': {
      apiKey: 'my_api_key'      
    }
  }
}

package.json:

"ember-simple-auth": "1.0.1",
"torii": "0.6.1"

controllers/application.js:

import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Controller.extend(ApplicationRouteMixin, {
    session: Ember.inject.service('session'),
    torii: Ember.inject.service(),
    actions: {
        authenticateWithFacebook: function(){
          this.get('session').authenticate(
            'simple-auth-authenticator:torii',
            'facebook-oauth2'
          ).then(
            function(data) {
              alert('SUCCESS ' + data);
            },
            function(error) {
              alert('There was an error when trying to sign you in: ' + error);
            }
          );
        }
    }   
});

app/authenticators/torii.js:

import ToriiAuthenticator from 'ember-simple-auth/authenticators/torii';

export default ToriiAuthenticator.extend({
  torii: Ember.inject.service()
});

Although I can connect with facebook using just torii, this example fails with the following error:

Uncaught Error: Assertion Failed: No authenticator for factory "simple-auth-authenticator:torii" could be found!

Any ideas? I use the latest ember-cli version.




extract to normalizeReponse issue

I am migrating ember & ember-data from 1.12 to 1.13. During same, I got deprecation message to rename extract methods as normalizeResponse of serializer. After doing same I am getting following error.

Assertion Failed: You must include an `id` for list-item in an object passed to `push`

But there are few models for which I am adding ids in extract method. But now, ember is throwing above error for normalizeResponse. How can I correct same?




Allowing buttons to be clicked if one or more checkbox are clicked

I have in my page two buttons, edit and delete. Edit only should be clicked if one checkbox are clicked, and delete should be clicked if one or more buttons are clicked.

I think my solutions is wrong:

<li class="controller {{if editRecord '' 'controller__item--disabled' }}">Edit</li>
<li class="controller {{if destroyRecord '' 'controller__item--disabled'}}">Delete</li>

And i'm observing two times model.@each.checked:

editRecord: Ember.computed('model.@each.checked', function() {
  let count = 0;
  this.get('model').forEach((item) => {
      if (item.get('checked')) {
        count +=1;
      }
  });

   if (count === 1) return true;
   return false;
});


deleteRecord: Ember.computed('model.@each.checked', function() {
  let count = 0;
  this.get('model').forEach((item) => {
      if (item.get('checked')) {
        count +=1;
      }
  });

   if (count >= 1) return true;
   return false;
});

The problem is.. if i have 10 buttons and i need check each one.. this will be unmaintainable..

Thanks.




how to skip SASS compilation in Ember Broccoli build

I'm compiling an Ember.js app using broccoli and currently I'm working only on the JavaScript files. The SASS stylesheet files are not being changed at all, yet our Broccoli build is always building new CSS out of those stylesheets.

How do I turn this off?

How can I make Broccoli only build JavaScript files or only build SASS files? It's really slowing down my compile times when I change a JS file but a SASS file is compiled.




How to change the query to the data model in Ember?

I do a browser-based game using Ember.js. I have a lobby with a list of the leagues (model lague), the transition to a specific league, I need to get a list of players of this league. API to get a list of players looks/api/leagues/:leagueId/players. How do I get a model in ember. for coal of this type?




Ember: Detect when an object is saved

Somewhere in my ember code I have

myobject.save();

I want to detect when that saving is done. Because then the object has gotten an ID.

I know the save method returns a promise and I can use then() to execute code when saving is done. But that pattern won't work in my case.

Somewhere else in my code I am doing several things and then I want to get the ID of myobject. Then I might have to wait until the object has finished the save and has gotten the ID. I need the id because it shall be part of a transition to a dynamic route. The code in a route action handler looks like this:

myobject.DoSomeStuffAndThenSave();
....
// Do some other stuff that might take some time
....
this.transitionTo('myroute', myobject.get('id'));

I guess I need to check the isSaving flag and and in the case the isSaving flag is true, I should listen to the isUpdated event. But how do I do that?




Ember simple auth 1.0.1 custom authenticator

I am updating my existing code done in ember-simple-auth: 0.8.0 to ember-simple-auth: 1.0.1

There are two problems

  1. It is not persisting a session
  2. REST Calls needed to be having withCredentials: true, not sure where I can set them.

Here is my code

//config/environment.js
  ENV['ember-simple-auth'] = {
    store: 'simple-auth-session-store:local-storage',
    authorizer: 'authorizer:custom',

    routeAfterAuthentication: '/dashboard',
    routeIfAlreadyAuthenticated: '/dashboard'
  };

My authenticator

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

export default Base.extend({
  restore(data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      }
      else {
        reject();
      }
    });
  },

  authenticate(options) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        type: "POST",
        url: config.serverURL + '/api/users/login',
        data: JSON.stringify({
          username: options.identification,
          password: options.password
        }),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json'
      }).then(function(response) {
        Ember.run(function() {
          resolve(response);
        });
      }, function(xhr) {
        Ember.run(function() {
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });
  },

  invalidate(data) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        type: "POST",
        url: config.serverURL + '/api/users/logout'
      }).then(function(response) {
        Ember.run(function() {
          resolve(response);
        });
      }, function(xhr) {
        Ember.run(function() {
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });
  }
});

My authorizer (you can see that I am trying to update my old code)

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

export default Base.extend({
  authorize(sessionData, block) {
    if (!Ember.isEmpty(sessionData.token)) {
      block('X-CSRF-Token',  sessionData.token);
      block('Content-Type',  'application/json;charset=utf-8');
      block('withCredentials', true);
    }
  }

  //authorize(jqXHR, requestOptions) {
  //  if (!(requestOptions.data instanceof FormData)){
  //    requestOptions.contentType = 'application/json;charset=utf-8';
  //  }
  //
  //  requestOptions.crossDomain = true;
  //  requestOptions.xhrFields = {
  //    withCredentials: true
  //  };
  //
  //
  //  var token = this.get('session.token');
  //  console.error(jqXHR);
  //  if (this.get('session.isAuthenticated') ) {
  //    jqXHR.setRequestHeader('X-CSRF-Token', token);
  //  }
  //}
});

My application adapter

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

    export default DS.RESTAdapter.extend(DataAdapterMixin, {
        authorizer: 'authorizer:custom',
        namespace: 'api',
        host: config.serverURL,
    });

Dashboard

    import Ember from 'ember';

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

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

        needs: 'application',
        setupController: function(controller, model){
            this.controllerFor('application').set('pageTitle', 'Dashboard');
            this._super(controller, model);
        }
    });

If I do console.log(this.get('session.isAuthenticated'); it returns me true, but when I use that in template it dont work

    {{#if session.isAuthenticated}}
        1
    {{else}}
        0
    {{/if}}

On my laravel end, i can see that session is created and user is logged in, on Ember side, it was previously setting the session and then resends the credentials with each request. Now when it send another request. I think it is without credentials: True and laravel returns 401. I also tried sending a garbage header and laravel CORS refused that it is not in allowed headers.

Thank you




how to upload an image using ember-cli-file-picker to the sails server and set one-to-one relation ship with its model and another model

i am trying to upload an image to sails server using ember-cli-file-picker from ember, its successfully uploaded to the sever but couldn't connect its model with another model,

/*************** Ember ********************/

// project mode


import DS from 'ember-data';

var attr = DS.attr;
export default DS.Model.extend({
  proImage:DS.belongsTo('pro-image',{ async: true }),
});



// project-image  model
import DS from 'ember-data';
var attr = DS.attr;

export default DS.Model.extend({
        proUrl: attr('raw'),
        proImageID:attr(),
        project:DS.belongsTo('project',{ async: true }),
        
});

how to get the image and its related project get together




Ember js: Setting a property only once (in an observer) throws Deprecation Warning You modified X twice in a single render

I am running into quite some peculiar behavior. The thing is I understand the deprecation warning, however, it should not be happening as an 'observes', IMHO, does not use a getter, so, setting a property should not cause the deprecation.

I am using Ember 2.2.0 and Ember-Cli 1.13.8. Everything is structured in Components and, if need be, Services (global singletons). Here's a simplified version of my code. I should maybe make a JSFiddle and try to reproduce it, but I figured someone might spot the error directly.

Parent component template:

{{my-component model=service.currentModel changed=changed}}

my-component.js:

watchChanged: function() {
    this.set('model', this.get('some_internal_value')); //this throws deprecation, even though it should not
    this.get('parentView').send('resetChanged'); // reset changed in the parent
}.observes('changed', 'some_internal_value')

I went with the debugger and watchChanged is called EXACTLY ONCE, in spite of this fact, the deprecation warning is thrown. The code works perfectly, save for the deprecation warning. Any ideas?

My workaround is to do the set as a task in the 'afterRender' queue, but this isn't a solution for the issues that I am experiencing.

What is the "ember-way" in this case? Is it a bug or a lack of understanding on my side?

Edit: cross-posted it here.




Ember: change route event from outside the app

Here is the context. I'm developing an Ember app, that will be embed in a Drupal page. Only problem: the menu of the app must be in the drupal page.

So I'm trying to find a way to update the url of the page (from outside the app) and to get the event of changing url inside Ember so I can then apply the route as usual.

I tried:

  • history.pushstate(). But it doesn't trigger "popstate" so I can't really get any callback.
  • use "hash" url type in ember config, and then get the hashchange event from inside Ember. It works but I'd like to use the "history" url type

I have to try:

  • in Ember app, get the click event on the outside menu, and apply my routes. (But it doesn't seem like a really clean solution, does it ?)

Any ideas I can get to do that ?

Thanks for your help !




Emberjs : Global menu is not included in every page

I'm trying to make a global menu with emberjs. Following these instructions, I have written a controller/navigation.js and a views/navigation.hbs which render a fixed menu defined in the controller.

I then render the navigation template in application.hbs like so:

<nav class="navbar-default navbar-static-side" role="navigation">
    <div class="sidebar-collapse">
        {{render 'navigation'}}
    </div>
</nav>

When I load up the application at the root url, the menu is rendered as it should. However, as soon as I navigate elsewhere (by clicking an element of the menu, for instance), the menu is not rendered anymore, and if I navigate back to the home page later, the navigation menu is not rendered again.

Why isn't this template rendered every time application.hbs is rendered? What steps should I follow to make sure this menu is rendered with the application?

If it is possible, the navigation menu should have its own controller and template, in order to avoid having all that code in the application controller and template.




multiple tables on one template

When I render two or more tables on same template I get several deprecations like this one

DEPRECATION: You modified (mut bodyContent) twice in a single render. This was unreliable in Ember 1.x and will be removed in Ember 2.0 [deprecation id: ember-views.render-double-modify]

Furthermore, tables are loading very slow, they are buggy and unreliable - most of the time tables are populated with data, but it even happens that they stay empty - like there is a race condition problem.

Does anyone have an idea what could be a problem?




dimanche 29 novembre 2015

Ember data route with handler and api call in different location

Im new to Ember development and trying to build an Ember app using Ember data which connects to an API.

My API in the location http://localhost:3000/api/panelists returns

{  
   "panelists":[  
      {  
         "id":1,
         "secret":"",
         "isDisabled":"false",
         "disabledAt":"null",
         "isLocked":"false",
         "isSecretExpired":"false",
         "invalidAuthCount":"0",
         "givenName":"Sma",
         "middleName":"na",
         "surname":"ran",
         "avatarMimeType":"JPEG",
         "avatarFilePath":"/home/sample.jpeg",
         "createdAt":"2015-11-27T12:17:05.000Z",
         "isDeactivated":"false"
      }
   ]
}

Now in my Ember App, the model handler for this case is in the following location, App_Root/app/panelists/model.js

The specific required route is in the following path, App_Root/app/directory/route.js

Now, how do I hit the API http://localhost:3000/api/panelists with model App_Root/app/panelists/model.js and with the route App_Root/app/directory/route.js?

Current Implementation: route.js

import Ember from 'ember';

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

Getting the following error in browser:

WARNING: Encountered "panelists" in payload, but no model was found for model name "panelist" (resolved model name using golf-digest-panelists@serializer:-rest:.modelNameFromPayloadKey("panelists"))

Error while processing route: directory Assertion Failed: You must include an 'id' for undefined in an object passed to 'push' Error: Assertion Failed: You must include an 'id' for undefined in an object passed to 'push'
    at new Error (native)
    at Error.EmberError (http://localhost:4200/assets/vendor.js:24738:21)
    at assert (http://localhost:4200/assets/vendor.js:14639:13)
    at Object.assert (http://localhost:4200/assets/vendor.js:22040:34)
    at ember$data$lib$system$store$$Service.extend._pushInternalModel (http://localhost:4200/assets/vendor.js:72829:15)
    at ember$data$lib$system$store$$Service.extend.push (http://localhost:4200/assets/vendor.js:72815:34)
    at http://localhost:4200/assets/vendor.js:67700:17
    at Object.Backburner.run (http://localhost:4200/assets/vendor.js:9710:25)
    at ember$data$lib$system$store$$Service.extend._adapterRun (http://localhost:4200/assets/vendor.js:73042:33)
    at http://localhost:4200/assets/vendor.js:67697:15

Thanks in advance for the help




Unpermitted Parameters when working with EmberJS

I'm trying to learn how to use emberjs as a client of a rails api!

My code lives here: http://ift.tt/21nJf1w

Is a simple rails-api that provides CRUD operations by the restful endpoints. I'm following this tutorial but when I try to save a comment in blog post, I receive a Unpermitted params: :post.

How can I solve this problem?




Can't change session service name in torii

I'm using ember-simple-auth and emberfire to authenticate users on my app. One thing I don't like about the defaults is that there is both a "session" service and a "session" object on the service. So, I opened config/environment.js and changed:

var Env = {
  torii: {
    sessionServiceName: 'session',
    providers: {
      'firebase-simple-auth': {}
    }
   }
 ...

to

var Env = {
  torii: {
    sessionServiceName: 'auth',
    providers: {
      'firebase-simple-auth': {}
    }
   }
 ...

But, the newly named "auth" service doesn't have the "invalidate" and "authenticate" methods. Those are still on the "session" service (which I'm surprised is still around).

How do I move the entire "session" service over to an "auth" service?

Thanks!




Ember Error in Route Model

I am digging into Ember and am trying to serve a list of content to my route model. Here is my App.js code:

var App = Ember.Application.create({});

    App.Router.map(function() {
        this.route('about');
        this.resource('blogs');
        this.resource('projects');
    });

    App.PROJECTS = [
        {
            "id": 1,
            "title": "SnapFoo - SVG Animation Library",
            "textone": "SnapFoo",
            "texttwo": "SVG Animation Library",
            "image": "snapfoo.jpg"
        }
    ];

    App.ProjectsRoute = Ember.Route.extend({
      model: function() {
        return App.PROJECTS;
      }
    });

The PROJECTS array is abbreviated in terms of content but that's the format. Now, I am trying to run my each loop in the Hanldebars template like this:

<script type="text/x-handlebars" data-template-name="projects">
 {{#each}}
  <div class="project-icon">
   <span>{{textone}}</span>
   <span>{{texttwo}}</span>
   <a href="project.php?id=1"><img {{bind-attr alt="title" src="image"}}/></a>
  </div>
 {{/each}}
</script>

However, when doing this, the error I receive is Uncaught TypeError: Cannot read property 'addDependency' of undefined coming from ember.min.js.

If I remove the {{each}} loop, the error goes away which leads me to believe this has something to do with the model in the route. But any advice would be very helpful. Thanks!




samedi 28 novembre 2015

emberjs - refactor custom link-to to htmlbars

Previously I had my own custom link-to helper that I blogged about here.

With handlebars I could pass arguments that would cause a re-render if the value changed, for example if I am binding to model that has isLoaded=false, then the LinkView view would re-render when isLoaded=true or the value changed from undefined to its value.

Below is my old handlebars custom link-to helper

Ember.Handlebars.registerHelper('resource-link-to', function(path, options) {
  var args = Array.prototype.slice.call(arguments, 1);
  var resource = this.get(path);
  var resourceRoute = resource.humanize();

  if (!options.fn) {
    options.types = ['STRING', 'STRING', 'ID'];
    options.contexts = [this, this, this];
    args.unshift(path);
    args.unshift(resourceRoute);
    args.unshift(resource.get('displayName'));
  } else {
    options.types = ['STRING', 'ID'];
    options.contexts = [this, this];
    args.unshift(path);
    args.unshift(resourceRoute);
  }
  return Ember.Handlebars.helpers['link-to'].apply(this, args);
});

The ID marker in this line meant it was a binding:

options.types = ['STRING', 'STRING', 'ID'];

I am trying to replicate this in htmlbars in ember 1.13.11 and I have extendted the LinkComponent and overriden willRender like this:

export default LinkComponent.extend({
  willRender() {
    // FIXME: allow for css classes and query params
    Ember.assert('you must specify a resource', this.attrs.resource);

    const resource = this.attrs.resource;

    let resourceRoute = resource.value.humanize();

    if(typeToLinks[resourceRoute]) {
      resourceRoute = typeToLinks[resourceRoute];
    }

    this.set('attrs', {
      params: [resource.value.get('displayName'), resourceRoute, resource],
      view: this.parentView,
      hasBlock: false,
      escaped: true
    });

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

I then call it like this:

{{resource-linkto resource=activity.reference}}

The problem is that the resource might be in an isLoading state or partially resolved.

How can I trigger a re-render when the value is resolved?




cant get the model value in template

just started to play with emberjs.dont know if this is stupid question or good one, but I am stuck in this for some days and cant figure out why.

in my router.js

Router.map(function() {
  this.resource('posts', {path: '/'});
  ..........
  });

  .....
  this.resource('post', {path: 'posts/:post_id'});
});

and in the route folder i have posts.js setup as following.it has simple js varible used to hold id , title, and body of articles.

export default Ember.Route.extend({
    model: function(){
         var posts = [
        {
        id:'1',
        title:'lipsome vesicle',
        body:"A liposome is a spherical vesicle"},      
        {
        id:'2',
        title:'another lipsome vesicle',
        body:"A liposome is a another vesicle"}
]
    //console.log(posts)
        return posts;
    }
});

In posts.hbs, the title of each post is shown as link to the to post. of course by looping through each model as |post| and print link-to post.title.

my post.js file simply get the model for posts and returns it.

export default Ember.Route.extend({

    model: function(params) {

        return this.modelFor('posts').findBy('id', params.post_id);
    }
});

In my template for post.hbs I wanted to simply show the title and body for the post .It would have been more redable if it was like post.title or something like that. but i saw some tutorials that does following.

 <h1>{{title}}</h1>
    <h1>{{body}}</h1>

the url goes to the localhost:4200/post/1 but I cannot see the title and body

when I checked the value in console for

 this.modelFor('posts').findBy('id', params.post_id).title , it prints the title

but view is blank. I have read somewhere, that the controller is the one that is responsible to get the value from model. in that case too, I dont know how to access the returned model in that controller.

I have watched many tutorials, including the raffler example by railscast, since I have background in rails. but those tuts including lot other seems preety outdated. So for all new learners this is frustating and confusing too. Is there good fresh resources except the emberjs guide?




How to hide navbar in application template if the route is login

I have in my application template:

<nav class="navbar">
  <!-- etc -->
</nav>
{{outlet}}

And in the login template, i don't want show the nav, so.. how exactly i could do this?? I searched but there isn't much resources.

The only solution i create is take off the nav and put in all templates, except for the login.. But i feel that i'm doing it wrong.. That Ember could help me achieve this using build in methods.

Thank you in advance!!




Ember action passing null

I have the following:

Two models belonging to each other

export default DS.Model.extend({    
            cv: DS.belongsTo('cv'),

export default DS.Model.extend({  
            title: DS.attr('string'),
            personalDetail: DS.belongsTo('personal-detail'),

and a route with the following

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return this.modelFor('build').get('personalDetail'); 
},
    actions: {
        saveDetails(mod)
        {
            const details = this.modelFor('build').get('personalDetail');

        }
    }
});

In the Hbs

  <div class="row">
        <div class="col-xs-2 col-xs-offset-9">
            <button {{action "saveDetails" model on="mouseUp"}} class="btn1 btn--white-blue big right">
                NEXT
                <span>
                    <svg role="img" fill="currentColor">
                        <use xlink:href="icons/icons.svg#arrow-down"></use>
                    </svg>
                </span>     
            </button>
        </div>
    </div>

So what happens here is that I have a root object called cv and has a belongs to relationship to persontalDetail

when I call the info route it gets the model for the build route(which is a parent route) which is the cv object, from there it gets ther personalDetail model and passes it on to the page.

When I click on the savedetails I'm expecting the model to be returned to the method but for some reason a null is being passed.

I have a similar setup on other pages for objects with a has many relationship but I cant get it to work with the above.

Any ideas on what I am doing wrong?




Using different prototypes depending on type in Ember

Im playing around with Ember.js atm and Im not really used to the concept so far. What I want to do now is to build a little cms and I need something like a Class or Object depending on the type of content. E.g. I load up an element of the type text, this type has some content. Another Element is of the type Section, this has the attributes size, color and whatever. What I need now is to let the route decide, what kind of content it has loaded, and depending on that build omething new with the special properties. Let's say

Ember Route loads content, looks up type
  if type == text
    make a new text-oject/class with properties name, heading, content

  if type==section
    make a new section-object/class with properties color, size etc.

How do I achieve this in Ember, so that I have some kind of prototype for each content-type, and load the used properties from different db-relations?




Ember programatically pass data between components

I have two ember components, one to show video card (video-card) and another to show video modal (video-modal) when playing the video. What I want to achieve in Ember is to be able to pass to the video-modal the video object the model should currently play. As for now I wasn't able somehow to bind the video object from the video-card to the video-modal.

/components/video-card.js

import Ember from 'ember';

export default Ember.Component.extend({

    actions: {
        play: function(){
            // outputs video title when video thumbnail is clicked
            console.log(this.get('video').get('title')); 
            Ember.$('#video-modal').openModal();
        }
    }

});

The only thing these components have in common is the /controller/application.js controller because the components are inserted in different parts of the tempalte:

/tempaltes/application.hbs

{{video-modal}}

/templates/index.hbs

{{#each model.videos as |video|}}
<li>
  {{video-card video=video}}
</li>
{{/each}}

Ho to bind the video object from video-card when play() action is triggered, to the video-modal component dynamically?




Change the font size from one component to another component

I want to change the font size from one component to another component.
I have comonent - "chande-font-size".

chande-font-size.hbs

<button>+</button><button>-</button>

And component - "example-text".

example-text.hbs

<p class="special-text">some text</p>.

Component chande-font-size does not see html DOM of example-text component.

Ember generate DOM dinamic, and we does not have document.ready.

An example of what I need - http://ift.tt/1kYL4Bn




Not able to call my api throwing error Disallowed for cross-origin requests that require preflight

Hey I am new to ember and frontend thing.My backend is designed using django.All my api endpoint ends with " / "(ex:http://ift.tt/1hY3S2b).Now when I call this api's from ember app.It send the requests to "http://ift.tt/1OlP1vf" and leaves the end " / ".

some codes snippet are:

routes.js:

return this.store.findRecord('feed');

model name is feed.

adapter.js:

host:"http://example.com/api",
headers:{'authorization:"abc"}

THE ERROR IN CONSOLE IS:

The request was redirected to 'http://ift.tt/1hY3S2b', which is disallowed for cross-origin requests that require preflight.

So it is redirecting to correct api end point but cors is not allowing the requests to happen.

Is there a way to call the api with " / "at end through ember.




Ember component event not tirggered

I have a sidenav component with a toggle button to open or close it.

/templates/components/side-nav.hbs

<div class="sidebar">
  <span role="button" class="toggle-menu svg-icons" {{ action 'toggle' on='click' }}></span>
</div>

components/side-nav.js

import Ember from 'ember';

export default Ember.Component.extend({
    actions: {
        toggle: function(){
            console.log('click');
        }
    }
});

/templates/application.hbs

<div class="wrapper">
    {{side-nav}}
    {{outlet}}
</div>

The event is not fired no matter what. I know this is basic stuff, but I've spent hours not being able to make it work.




vendredi 27 novembre 2015

Ember normalize response

I'm extending the JSONSerializer in order to fit my server response which looks like this:

{
  "result": {
    "items": [
      {
        "id": "...",
        "title": "...",
        ...
      },
      ...
    ],
      "total": number,
      "...": "..."
  }   
}

therefore I have overridden normalizeResponse() method:

normalizeResponse: function(store, primaryModelClass, payload, id, requestType) {
        payload = payload.result.items;

        return this._super(store, primaryModelClass, payload, id, requestType)
    },

after this my model data fields are all undefined. What I'm doing wrong?




How to use ember select for static dropdown?

This has to be easy, but I'm failing.

I have this in a template:

<select {{action 'setType' this value="target.value"}}> <!-- I've tried various things for the value -->
  <option value="0">Choice 1</option>
  <option value="1">Choice 2</option>
</select>

I have this in a controller:

setType: function(mymodel, type) {
  mymodel.set('type', type);
  mymodel.save();
}

The action is firing, the model is available, but none of my guesses are sending the value of the select to the controller action.

I'm using Ember 1.13.7




Modify specific record from an array (method PUT)

I have Model "user" and I have a model that includes an array of objects:

{users: [
 {
   id: 1,
   name: user1,
   status: new
 },
{
   id: 2,
   name: user2,
   status: new
 },
...
]}

But, I have to change the status of a single user. I try:

 actions: {
    checkAccept(id) {
      this.store.findRecord('user', id).then((record) => {
        record.set('status', 'accepted');
        record.save();
      });
 }

With the same method to remove the recording works if used record.DestroyRecord. Why instead PUT method sent GET ???




Not able to make the right requests to backend in ember

I am new to ember and javascript.I have to make request to backend api (http://ift.tt/1NS6RkP).But the requests which ember is making is (http://ift.tt/1PeQhl5).Slash is getting removed after PROFILE.How to send the correct request.

adapter.js(profile.js)

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
     namespace: 'users',
    // token:this.store.find('application',token),
    headers:{"Authorization":"token b0fb466a6eac3ad87cd2000580b2192b85ab4"},
    host: 'http://example.com/api'
});

model.js(profile.js )

import DS from 'ember-data';

export default DS.Model.extend({
  dp_url:DS.attr(),
  full_name:DS.attr()
});

Route.js(feed.js)

import Ember from 'ember';

export default Ember.Route.extend({
    model(){
      var inflector = Ember.Inflector.inflector;
      inflector.uncountable('profile');
      return this.store.find('profile',{targetuser:-1});
   }
});

And is there a way in which I give a different name in this.store.find('different Name').As it get attached to the requests I made to backend.




jeudi 26 novembre 2015

Ember Integration Test: Promise rejected before it renders

Strange error started occurring in my Ember.js (2.2) application. I created a new component that uses a global library (e.g. Bloodhound). Suddenly some of my other UNRELATED/UNTOUCHED component integration tests stopped working, returning the following error: Promise rejected before it renders: Assertion Failed: You cannot use the same root element (#ember-testing) multiple times in an Ember.Application

I don't know if this is some sort of race-condition or threading issue while executing my tests using ember test. Very strange.

I'm currently trying to figure out how to deal with my global library situation, this is an existing & recently updated app...I can't make enormous changes right now. And I certainly can't abandon this new component because it was needed...what to do?




Is their any way to call ember-selectize action into controller?

I am new to ember development. I have to call action on the ember-selectize, but I am not getting where to write that action code?

{{ember-selectize
          id = property
          content = contentFromMyComponent
          optionValuePath = "content.id"
          optionLabelPath = "content.display"
          placeholder = "Select a thing"
          select-item=(action 'selectThing')
       }}

Where the action selectThing should be define?

Thanks!




How to access a route of an Ember application built with Ember-CLI from custom HTML?

My intention is to create a working island of richness in a PHP based web application built with Yii 2.

That means I have a route, say /cars/index, that is currently being rendered server-side by Yii. Now I want to move the Yii template code to an Ember template.

The Ember code is assembled using Ember-CLI's ember build. I have created softlinks from inside the Yii public web directory to the two Ember files dist/vendor.js and dist/app.js so that the code can be accessed from a web browser. For this storeConfigInMeta: false had to be set as depicted here: ember-cli meta config/environment file.

While I have successfully got Ember to run my code by using the ember-islands addon the goal is to keep the MVC structure, making use of the Ember application's models and controllers. This is to allow for a potential full shift to client-side rendering in the future, and it cannot be achieved with components only.

Unfortunately all I found when researching this topic was that I had to disable the creation of an Ember.Application and then create such an object by hand. This approach does not fit my use-case because that way I cannot make use of Model and Controller code in the server-side templates. Or can I?

Plus, how can we then route to /cars/index without letting the framework throw an error about Yii's route not matching this format (currently something like /index.php?r=cars/index)? (Uncaught UnrecognizedURLError)




Mimicking the Facebook app's infinite stack in Ember.js

Ember routing works nicely when working with strict linear paths of resources. However, it's becoming more prevalent in mobile design for apps — such as the Facebook app — to use infinite stacks of multiple interconnected resources:

Example Facebook infinite stack

  1. User starts in the feed.
  2. Presses on a link to a user profile.
  3. Navigates to user's list of friends.
  4. Visits a new user profile.
  5. Goes to any other types of resources such as posts, groups etc.
  6. THEN can navigate all the way back with each page state persisted.

We start off in a known resource - let's say it's Facebook's news feed. In Ember, we'd define that route as:

this.route('feed');

But from there, we'd like to be able to visit any combination of our resources - whilst still maintaining the state of each route. The temptation is to solve the problem through some funky route solution, such as using catch-all route definitions:

{ path: '*' }

But that'd take some heavy path management as discussed here (or perhaps there's some method of utilising Tilde's router.js URL generation?!). But as per the illustrated example above, it would leave us with huge goddamn route paths:

/feed/users/:user_id/friends/users/:user_id/another_resource/:another_resource_id

Not that that's a problem in a mobile app, but I'm not sure if it's the optimal way of achieving this.

So that leads me to consider whether there's some method of dynamically creating outlets as stacks get deeper (akin to modals) - or whether the only way to achieve state persistence is using an app level object, Ember data or an Ember service to track history.

Anyway, tl;dr, I'm not desperately needing this functionality - just interested if anyone has a smart insight into how achieve this ...umm ... infinite interconnected nested resource stack thingy.




How to query with equalTo in emberfire?

I'm trying to make a trully simple query with Emberfire, but it's not working. No console errors, it just doesn't do a thing.
My versions are Ember 2.2.0, Ember-data 2.2.0 and EmberFire 1.6.1
My data is something like the folowing:

{
  'data':[{
   'element' : 0 
  },{
   'element' : 1 
  },{
   'element' : 1 
  },{
   'element' : 0 
  },{
   'element' : 2 
  }]
}

And my query in Ember would be something like this:

export default Ember.Route.extend({
  model(){
    return this.store.query('data', { orderBy: 'element', equalTo: 1 } );
  }
});

The results, passing trough an each loop, are looking like this

0 0 1 1 2

Only works the orderBy part, not the equalsTo. Any suggestions?




Ember: same route, different paths

I would like a route to be called in 3 different ways:

  this.route('issue', {path: '/foo/:param1'});
  this.route('issue', {path: '/foo/:param1/:param2'});
  this.route('issue', {path: '/foo/:param1/:param2/:param3'});

But when I try to link-to for example using:

{{#link-to 'issue' issue.id issue.tag}}{{/link-to}}

I get this error:

Error: You didn't provide enough string/numeric parameters
to satisfy all of the dynamic segments for route issue

I tried to change the order of the calls in the router, without success. I think I'm lacking some comprehension on how the routes are detected. Any ideas?




How to add templates to sub-directories in Ember?

I am quite sure the answer to my question is somewhere in some docs, I read many pages, on official and unofficial websites, many related questions on SO, but my google-fu seems not developed enough to help me find the answer, so here I am.

In my team we are using Ember-cli for some web application. We have the classic app/templates folder in which we put the .hbs of each "controller" we have. In those handlebars templates, we use components which are in app/templates/components.

We recently have reached a point where the app/templates/components is too big. I thought that it would be good idea to split them into sub-directories, e.g.

  • app/templates/product1 containing specific-to-product1 components + the base product1 handlebar (the one called in app/router.js, a "controler's hbs").
  • app/templates/product2 containing specific-to-product2 components + the base product2 handlebar (the one called in app/router.js, a "controler's hbs").

But when I do that, it doesn't work and displays a white page:

  • If I move the "controler's hbs" from app/templates to app/templates/product1, I have a whole white page with nothing loaded.
  • If I move a component from app/templates/components to app/templates/product1, the "controler's hbs" shows, but I have an empty block where my component is supposed to be.

I don't know if I have to configure ember for it to recursively search for handlebars in the app/templates folder, and/or if I have to change the router.js, and how to call my components so ember knows where they are.

Thanks in advance,

Benjamin




how to use another controller method in ember

im' trying to use a method which is in application.js, is these a controller. it has a method called isAuthenticated which return if a user is login or not.

in my application.hbs it works fine, but when i call it in my posts/new.hbs it always return false. why it?

my application controller,

import Ember from 'ember';
import App from '../app';

export default Ember.Controller.extend({
  authManager: App.AuthManager,

  currentUser: function() {
    return App.AuthManager.get('apiKey.user');
  }.property('authManager.apiKey'),

  isAuthenticated: function() {
    return App.AuthManager.isAuthenticated();
  }.property('authManager.apiKey'),
});

solutions?




Ember JSONSerializer conditional embedding

Is it possible to have conditional embedding in JSONSerializer? In my app I have some model relationships I don't wish to include on some pages.

For example:

video detail page this.store.query('video', {filter: {include: 'tags'}}), here the tags should be embedded

search results page this.store.query('video'), here tags should NOT be embedded.

Defining:

import DS from 'ember-data';

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

will always embed tags into any video model, and so calling this.store.query('video') will throw an error because the tags attribute will not be present in the response.




Handlebars dont wait for Ember Ajax

My Problem is that the handlebars is not wating for the ajax request to be finished.

My console is like this:

  1. It starts with "starting" from the function in the controller.
  2. Then the {{log workouts}} in the template which is undefined because the ajax is yet not ready.
  3. And at the end the data from the request.

So this is a part of my code of my workouts controller

workouts: function() {
        console.log("starting");

        this.get('session').authorize('authorizer:custom', (headerName, headerValue) => {
            var obj = {};
            obj[headerName] = headerValue;

            Ember.$.ajax({
                type: "GET",
                url: this.requestEndpoint,
                headers: obj,
            }).success(function(data) {
                console.log("ajax: "+JSON.stringify(data));
                return data;
            }).error(function(error) {
                return error;
            });
        }); 
  }.property()

And the Handlebars Template is like this:

{{log workouts}}

How do I solve this? Maybe: Is there a way to transform this code into a promise? Or is there a "wait for ember" option?




Future Development in UI using client side MVCs(backbone,angular)

I've a doubt, I'm a UI Developer. I dont know anything about server side. So Is Backbone or other MVCs useful for me in future particularly UI Development?




Ember data dynamic model not loaded in the store

I have a search model in my app which loads dynamically when the users types something in the search box. The this.store.query('search', {query: "xyz"}) is called on keyUp() and fetches the data from the API backend. However, looks like I'm missing something here because in Ember Inspector I don't see the data to be loaded for the search model. Anyway, this is not my biggest concern because I don't know if ember inspector loads data from the store dynamically or only on refresh. My problem is that I can't access the data returned from the server in the template.

I have to mention that I don't have a route for search results, this is more like IMDb-like search box, where the results are loaded as search box kind of autocomplete instant results.

My code:

/templates/components/search-box.hbs

{{input value=query}}
<div>
  // search results should be displayed here
</div>

/templates/components/app-bar.hbs

<nav>
    {{#link-to 'index' tagName='button'}}Home{{/link-to}}

    {{search-box value=query action="search"}}
</nav>

/templates/application.hbs

{{app-bar action="search"}}
{{outlet}}

/components/search-box.js

import Ember from 'ember';

export default Ember.TextField.extend({

    keyUp: function(e){
        if (this.get('value'))
            this.sendAction('action', this.get('value'));
    }

});

/components/app-bar.js

import Ember from 'ember';

export default Ember.Component.extend({

    actions: {
        search: function(query){
            this.sendAction('action', query);
        }
    }
});

/controllers/application.js

import Ember from 'ember';

export default Ember.Controller.extend({

    actions: {
        search: function(query){
            this.store.query('search', {text: query});
        }
    }
});

Shouldn't this.store.query('search', {text: query}); automatically push records into the store? If it does, how can I access them inside my /templates/components/search-box.hbs component?

Thank you!




jQuery Ajax: Variable as Header key

So currently im working with emberjs and i try to set the header of a request this way with variables:

 Ember.$.ajax({
            type: "GET",
            url: this.requestEndpoint,
            headers: {`${headerName}`: headerValue}
        })

But the problem is that in headers: {`${headerName}`: headerValue} the ` is a unexpected token. Do you have an idea to solve that problem?

Edit: Just to make sure headerName and headerValue are the variables.




Ember 1.13.8 - {{em-form}} values not updating after clicking save

Using the package - http://ift.tt/1MT4ONu. I am trying to save some information from the form

{{#em-form action="submit" model=model submit_button=showSubmitButton}}
   {{em-input type="text" property="username" label="username" }}
   {{em-input type="email" property="emailid" label="email" }}
   {{em-input type="password" property="password" label="password"}}
   <button class="btn btn-primary"> save </button>
{{/em-form}}

I am trying to save the data and it's storing the data properly in the backend. For some reason it's not clearing the form values.

Right now i am using some kind of jugaad fix to remove those values after saving the data. Any help would be great.




mercredi 25 novembre 2015

Is there a way to wait/delay rendering until for #Each-Helper is done with provided model?

Background: In my application I want a list of tags that's being displayed on every page of the website. Therefore I added a component to my application.hbs and gave the model, which I received in my application-route (from Firebase), into it:

application.hbs:

{{#tag-list-slider model=model}}{{/tag-list-slider}}

application.js (Route):

model() {
    return this.store.findAll('tag')
}

Problem: In my component I want to display the given model with the bxSlider. This works fine as long as I have static content like this:

conponent.hbs:

  <ul class="tag-slider">
      <li class="listItem">foo</li>
      <li class="listItem">foo</li>
      <li class="listItem">foo</li>
      <li class="listItem">foo</li>
  </ul>

The slider works great for this, even with images. Now my problem comes up as soon as I want to fill that list with the content of the model I put into the component:

  <ul class="tag-slider">
      {{#each model as |tag|}}
        <li class="listItem">foo</li>
      {{/each}}    
  </ul>

...and the slider just won't work. I put the "logic" for the slider in my component.js and there I used the didInsertElement()-hook:

Ember.run.scheduleOnce('afterRender', function() {
  $('.tag-slider').bxSlider({
    slideWidth: 200,
    maxSlides: 2,
    slideMargin: 50
  });
});

As you can see I even tried to use 'afterRender', but that doesn't do anything for me.

(I think) I nailed the problem down to the slider not having all the list-items when the page gets rendered. For that I combined the two cases from above and filled the list with both dynamic content from the #each-helper and the static html-content. In my didInsertElement() I wrote the count of all the list-items to the console:

  var listLengh = $('.listItem').length;
  console.log(listLengh);
  // try again, just for safety:
  Ember.run.scheduleOnce('afterRender', function() {
    var listLengh = $('.listItem').length;
    console.log(listLengh);
  });

and for both console.logs the output is "4" although it should be 8 (4 static + 4 dynamic list-items) because I think the count happens before the #each-helper adds the dynamic content to the page. (Which is strange because I thought thats the didInsertElement-hook was for).

So I'm looking for ways to delay the whole bxslider-process untill my #each-helper is done with loading the model-data to the template but I couldnt really find anything thus far.

Any Ideas? Thanks in advance!




Cannot read property 'replace' of undefined API with ember

I'm receiving the following error when i try to edit and delete a record in Ember:

Cannot read property 'replace' of undefined

I'm using an API to GET, GET ALL, CREATE, UPDATE and DELETE.

The GET, GET ALL and UPDATE is working pretty fine, but the rest is throwing this error.. I was searching and i found out that my response object is wrong.. but i'm just returning what Mongoose is returning to me:

When i delete:

{ result: 
   { ok: 1,
     n: 1,
     lastOp: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1448505478 },
     electionId: 562020eaa64d1ba4e7af6f2a },
  connection: 
   EventEmitter {
     domain: null,
     _events: 
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options: 
      { socketOptions: {},
        auto_reconnect: true,
        host: 'ds053698.mongolab.com',
        port: 53698,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: {} },
     id: 4,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 53698,
     host: 'ds053698.mongolab.com',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'ds053698.mongolab.com',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        bytesRead: 509,
        _bytesDispatched: 682,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }

When i update:

{ ok: 0, n: 0, nModified: 0 }

Thank you!!




"(generated application controller)" displayed instead of value contents in Handlebars "#each" helper

I'm working with my application.hbs template in EmberJS, and working to create a dynamic dropdown menu that is populated by the model contents. My route/model is defined like:

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      dictionaries: ['One', 'Two', 'Three'],
      test: 'Value'
    });
  }
});

And in my template, if I use {{model.test}}, then it prints "Value" successfully. However: When I try to build a list using the values of model.dictionaries, both attempts fail, albeit differently.

This method:

{{#each model.dictionaries}}
    <li><a href="#">{{this}}</a></li>
{{else}}
    <li><a href="#" style="font-style: italic;">No values</a></li>
{{/each}}

Builds a list with 3 entries, but their contents are:

<li><a href="#">(generated application controller)</a></li>
<li><a href="#">(generated application controller)</a></li>
<li><a href="#">(generated application controller)</a></li>

And if I try instead to assign each item a name:

{{#each dict in model.dictionaries}}
    <li><a href="#">{{dict}}</a></li>
{{else}}
    <li><a href="#" style="font-style: italic;">No values</a></li>
{{/each}}

Then no values are displayed, resulting in:

<li><a href="#" style="font-style: italic;">No values</a></li>

What mistake am I making in attempting to iterate the model-provided array?




Ember Data, Normalizing Delete Response

On my api, I only get a 200 and 'success' message in my response. after calling DELETE on a record. I was wondering if there was some way to normalize this into a empty object that REST is expecting.

I've tried all the normalizeDeleteRecordResponse, normalizeSaveRecordResponse, but they don't seem to be catching.

Thanks in advance.




How to get model data on view in Ember JS

How can i access model data in my view template in Ember JS ? Is it saved in a global variable?

Here's my template:

<script type="text/x-handlebars" data-template-name="todo-list">
    {{#if length}}
    <section id="main">
        {{#if canToggle}}
        {{input type="checkbox" id="toggle-all" checked=allTodos.allAreDone}}
        {{/if}}
        <ul id="todo-list">
            {{#each}}
            <li {{bind-attr class="isCompleted:completed isEditing:editing"}}>
                {{#if isEditing}}
                {{todo-input type="text" class="edit" value=bufferedTitle focus-out="doneEditing" insert-newline="doneEditing" escape-press="cancelEditing"}}
                {{else}}
                {{input type="checkbox" class="toggle" checked=isCompleted}}
                <label {{action "editTodo" on="doubleClick"}}>{{title}}</label>
                <button {{action "removeTodo"}} class="destroy"></button>
                {{/if}}
            </li>
            {{/each}}
        </ul>
    </section>
    {{/if}}
</script>
<script type="text/x-handlebars" data-template-name="todos">
    <section id="todoapp">
        <header id="header">
            <h1>todos</h1>
            {{todo-input id="new-todo" type="text" value=newTitle action="createTodo" placeholder="What needs to be done?"}}
        </header>
        {{outlet}}
        {{#if length}}
        <footer id="footer">
            <span id="todo-count"><strong>{{remaining.length}}</strong> {{pluralize 'item' remaining.length}} left</span>
            <ul id="filters">
                <li>
                    {{#link-to "todos.index" activeClass="selected"}}All{{/link-to}}
                </li>
                <li>
                    {{#link-to "todos.active" activeClass="selected"}}Active{{/link-to}}
                </li>
                <li>
                    {{#link-to "todos.completed" activeClass="selected"}}Completed{{/link-to}}
                </li>
            </ul>
            {{#if completed.length}}
            <button id="clear-completed" {{action "clearCompleted"}}>Clear completed</button>
            {{/if}}
        </footer>
        {{/if}}
    </section>
    <footer id="info">
        <p>Double-click to edit a todo</p>
    </footer>
</script>

Thank you!




emberjs - layouts without views

I am upgrading an ember application from 1.7.1 to 1.13.13 and one technique I used to use to great effect is to use layouts in views, e.g:

App.UserView = Radium.View.extend({
  layoutName: "layouts/two_column"
});

With views deprecated in the latest ember, is there any provision for layouts?




how to scrolled to DOWN after updating the properties using ember

I am using ember view, once the page loads i want to scroll down to the page.In view didInsertElement will call and make the page load to scroll down, here is my code 

 App.MessagesView = Ember.View.extend({
  didInsertElement: function() {
    this._super();
    var $target = $('.chat-area .chat-list')
    ,   height = 0;
    if ($target) {
        $target.each(function(i, items_list) {
            $(items_list).find('li').each(function() {
                console.log($(this).height());
                height = height + parseInt($(this).height());
            });
        });
        $target.animate({ scrollTop: height});
    }
}

But once in controller if new other messages are loaded, because the view is already loaded ,the scroll bar is not scrolling down to the page.for the other message. the new messages are updated to the computed property and i want to call after the DOM messages are updated and call scrolldown code.

  App.MessagesController = Ember.ArrayController.extend({
    newmsgsCaptured: function(uuid) {
       this.setProperties({
                'newSelectedMessages': response,

            });

            var $target = $('.chat-area .chat-list')
            ,   height = 0;
            if ($target) {
                $target.each(function(i, items_list) {
                    $(items_list).find('li').each(function() {
                         console.log($(this).height());
                        height = height + parseInt($(this).height());
                    });
                });
                console.log(height);
                $target.animate({ scrollBottom: height});
            }

     } 
});

after calling newmsgsCaptured 'acction', the property is updated with new data and the scrolled down is not working.




Ember {include: property} and Strongloop

Ok, here is the thing, as I dig more into Ember and StrongLoop integration I find it more and more difficult to connect them both.

I have the following problem now. StrongLoop does not return the model relations based on JSONAPI format, so if my video model has a hasMany relationship with tag model, there will not be an include array in my response as specified here: JSON API docs.

So I have to options here: either async: true which makes 2 requests and is not desirable, or pass a filter parameter to the request like:

return this.store.queryRecord('video', {'include': 'tag'}); which will cast a request to /videos?include=tag but StrongLoop doesn't recognise this request.

Any thoughts?




How to customize the ember-cli-pace loader in ember application?

I installed ember-cli-pace addon into my ember application, want to change the default loader.

But not getting How and from I should change it.

I am using ember-cli with version 1.13.8




Ember-CLI project manage module dependencies

What is the best way to manage module dependencies in an Ember-CLI project ?

I am looking at Ember-CLI version 1.13.1 and above

Do libraries like module-js really help in managing dependencies ? http://ift.tt/1SjpYYK




mardi 24 novembre 2015

Compile template from another app directory

I have two ember-cli applications, ./my-app and ./new-app. In my-app, if I run ember build all my *.js files and *.hbs files gets compiled and stored as ./my-app/dist/my-app.js. Now I just want to include one .hbs file inside ./new-app/app/templates for my-app. For some reason I can't include that .hbs file in my-app. Any way to get it done? Should I have to configure any file?




Deleting data mongodb

When i'm deleting one collection in my MongoDB, i'm receiving this output:

{ result: 
   { ok: 1,
     n: 1,
     lastOp: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1448429280 },
     electionId: 562020eaa64d1ba4e7af6f2a },
  connection: 
   EventEmitter {
     domain: null,
     _events: 
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options: 
      { socketOptions: {},
        auto_reconnect: true,
        host: 'ds053698.mongolab.com',
        port: 53698,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: {} },
     id: 3,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 53698,
     host: 'ds053698.mongolab.com',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'ds053698.mongolab.com',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        bytesRead: 509,
        _bytesDispatched: 682,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }

And ember is complaining about it. When i delete, the delete will happen.. but will also pop up this error:

TypeError: Cannot read property 'replace' of undefined
    at Object.func (ember.debug.js:39371)
    at Object.Cache.get (ember.debug.js:13297)
    at decamelize (ember.debug.js:39408)
    at Object.func (ember.debug.js:39328)
    at Object.Cache.get (ember.debug.js:13297)
    at Object.dasherize (ember.debug.js:39412)
    at ember$data$lib$system$normalize$model$name$$normalizeModelName (normalize-model-name.js:13)
    at ember$data$lib$serializers$json$serializer$$default.extend.modelNameFromPayloadKey (json-api-serializer.js:272)
    at ember$data$lib$serializers$json$serializer$$default.extend._normalizeResourceHelper (json-api-serializer.js:149)
    at ember$data$lib$serializers$json$serializer$$default.extend._normalizeDocumentHelper (json-api-serializer.js:118)

And the return response is:

{"data":{"ok":1,"n":1,"lastOp":"6220957784033198081","electionId":"562020eaa64d1ba4e7af6f2a"}}

This is happening when i try to edit, too.

Thanks guys.




this.container.lookupFactory no longer works in ember@2.2.0

Since updating to ember@2.2.0, const config = this.container.lookupFactory('config:environment'); no longer works.

I can't use import ENV from 'your-application-name/config/environment'; because I don't actually know what the application-name is as I am using this in an addon and also some blueprints.

What is the alternative?




Edit nested route send params from checkbox checked

I have a list (table), with all my events within.:

CHECKBOX   NAME_OF_EVENT  DATE_OF_EVENT

This list is in my events/index. I would like to go to events/new, passing a parameter._id, and this parameter._id should be the column that have the checkbox clicked, like:

{{link-to 'events.new/ID OF CHECKBOX CHECKED' }}Edit{{/link-to}}

I am relative new to Ember, and I'm not finding a satisfactory answer, so I don't know exactly where I should start.

Thank you very much in advance.




How to detect a route change on foreign Ember application?

I'm trying to make a Chrome extension for Zendesk and it appears that their application is built with Ember. I used $(document).ready, but that is only really firing if I refresh the pages... otherwise it doesn't fire at all. How can I listen for page changes in Zendesk for my Chrome extension?

I looked around and only found answers that would help only if it was my own Ember app. Also, it isn't a hashchange.




Is it possible to remove the "Expected '{' and instead saw" error from Ember Cli?

I've just started working with Ember cli, and every time I change a file, it spits out JSLint errors found in that file.

This is extremely helpful, except for the fact that it considers the following to be in valid:

var isValidJS = true;

if (isValidJS) console.log("This is totally valid JS");

It responds with this error: Expected '{' and instead saw 'console'

Is there anyway to silence only the errors specific to missing curly braces?




Disconnecting a modal emberjs

Disconnecting this outlet (from my application route)

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

gives this error:

Uncaught TypeError: this.disconnectOutlet is not a function

How can I disconnect the modal outlet?

application.hbs:

{{outlet}}
{{outlet 'modal'}}




Action not being sent from component in EmberJS

When I close a bootstrap modal, it doesn't send the action it should (in application js:)

<li><a {{action "showSignInModal"}}>Sign In</a></li>
{{outlet}}
{{outlet 'modal'}}

bootstrap-modal.js:

this.$('.modal').modal().on('hidden.bs.modal', function() {
  alert("Closed");
  this.sendAction('removeModal');
}.bind(this));

routes/application.js:

export default Ember.Route.extend({
  actions: {
    showSignInModal: function() {
      this.render('components.signin-modal', {
        into: 'application',
        outlet: 'modal'
      });
    },
    removeModal: function(){
      alert("Working")
    }
    //...
  }
})

The "closed" alert shows, but the "working" alert doesn't. (The signin modal is a component, with no actions defined, and is just a bootstrap-modal)




How to have a favicon on my Ember app?

I know this seems like a simple question but I've tried many things and nothing seems to be working...

I have <link rel="shortcut icon" href="assets/images/favicon.jpg"> is my <head> tag but the favicon isn't showing.

The path to the image is \public\assets\images\favicon.jpg.

No errors whatsoever are shown anywhere.

Any idea why this is happenning and how can I solve it?




How can I differentiate between 2 routes in Ember when resetNamespace: true?

I'm putting together an Ember 2.2 project and I have a modal that I want to open from 2 different places (i.e. show and index). My Router looks like this:

Router.map ->
  @route 'rules', path: '/', ->
    @route 'index', path: '/', ->
      @route 'activations', resetNamespace: true
    @route 'new'
    @route 'show', ->
      @route 'activations', resetNamespace: true
    @route 'edit'
    @route 'schedule'

This works just as I'd expect when I enter the url in the address bar. However, when I use the link-to helper in a template, it always redirects to /show/activations even if I'm in the index route:

app/templates/rules/index.emblem

li: link-to 'activations' | activations

the above redirects to /show/activations rather than /activations as I'd expect.




attributeBindings and classBindings not appending to with component helper in Ember 2.1?

I have a widget dashboard app where the individual widgets are displayed using the component helper. A template ends up looking like this:

<div class="panel panel-default">
  <div class="panel-body">
    {{component model.displayComponent model=model}}
  </div>
</div>

A Widget instance will return a path for the displayComponent like: widgets/category/specific-widget.

What I'm finding, in Ember 2.1, is that the attributeBindings and classBindings defined on the component are not being applied. And I think they were being applied back in Ember 1.13.

In other words, in 1.13 think a component defined like this:

// app/components/widgets/category/specific-widget.js
export default Ember.Component.extend({
  model:      null,
  classNames: [ 'widget-content' ],
  attributeBindings: [ 'style:style' ],
  style:      Ember.computed.readOnly('model.contentHeight')
});

I would get a <div id="ember..." style="height:300px" class="ember-view widget-content">...</div>. Now I simply get the default <div id="ember..." class="ember-view">...</div>.

Am I mistaken about the old behavior? If not, is there a way to make this work the old way?

P.S. I'm unable to find the documentation for the component helper anywhere. Is that on the ember.js site?




Ember Component does not get model change

I'm relatively new to Ember.js and there are some things I dont really get so far. I use a component in my template and I pass in a model and a value. The value is used to filter the model (I also need the whole model, so i cant pass in the filtered version). When i first render it, everything is fine, but if I change the passed in value, the component empties the part, that relies on the model (hard to explain;))

index.hbs:

{{#content-view contents=contents parentId=sectionId}}{{/content-view}}

component.hbs:

<h1>Content</h1>
<p>{{parentId}}</p> //this part changes correctly
{{#each filteredContents as |fContent|}} //this part gets empty on change of parentId
    <p>{{fContent.type}}</p>
{{/each}}

component.js:

filteredContents: function() {
    return this.get('contents').filterBy('parentId', this.get('parentId'));
}.property('parentId')

As far as I get it now, the parentId is passed in correctly, and the first time the component is called, filteredContent also behaves correcty, but as soon as I change the parentId, there seems to be something wrong.




Ember template handlebars compile TodoMVC

I am working on Ember TodoMVC sample and trying to make the App template compiled : Here's a template example :

<script type="text/x-handlebars" data-template-name="todo-list">
    {{#if length}}
    <section id="main">
        {{#if canToggle}}
        {{input type="checkbox" id="toggle-all" checked=allTodos.allAreDone}}
        {{/if}}
        <ul id="todo-list">
            {{#each}}
            <li {{bind-attr class="isCompleted:completed isEditing:editing"}}>
                {{#if isEditing}}
                {{todo-input type="text" class="edit" value=bufferedTitle focus-out="doneEditing" insert-newline="doneEditing" escape-press="cancelEditing"}}
                {{else}}
                {{input type="checkbox" class="toggle" checked=isCompleted}}
                <label {{action "editTodo" on="doubleClick"}}>{{title}}</label>
                <button {{action "removeTodo"}} class="destroy"></button>
                {{/if}}
            </li>
            {{/each}}
        </ul>
    </section>
    {{/if}}
</script>

And then in my javascript code :

var source = $("#myapp").html(); // getting the template
var template =  Handlebars.compile(source); // compiling the template
var html = template(data); //serving the template as html with data

But template is a function which needs data parameters, So which data parameters needs to be set ?

Thank you!




Ember- update a model using updateRecord with values coming from the controller

In my signup.js route, I'm using the code below to fetch values from my signup.js controller, and then save a new record on the user model. It works fine.

actions: {
  save: function() {
    var userName = self.controller.get('userName');
    var userEmail = self.controller.get('userEmail');
    var userHeight = self.controller.get('userHeight');

    var user = this.store.createRecord('user', {
      name: userName,
      email: userEmail,
      info: {
        height: userHeight,
      },
    });
    user.save();
  },
}

Now I need to update the record from the edit-account.js route. The values coming from the controller will have been updated by the end user.

The additional field 'securityToken' needs to be included for security reasons (The end user must also fill this in).

actions: {
  save: function() {
    var user = this.get('model.user');
    var userEmail = self.controller.get('userEmail');
    var userHeight = self.controller.get('userHeight');
    var securityToken = self.controller.get('securityToken');
    
    this.store.updateRecord('user', {
      name: userName,
      email: userEmail,
      info: {
        height: userHeight,
      },
      confirm_user: securityToken,
    });
    user.save();
  },
}

I can't work out the correct way of doing this- I've tried many variations on the above, but they all give the error 'store is not defined'.

Is it possible to update an existing record with this kind of pattern?

Many thanks




Ember.JS value binding not working in Action

I am trying to get value binding working properly in my Ember app. The binding works on the input, as in, when I type text into the input field it displays next to "Your Goal:". However, when I click "Next Step", it is not displaying the value properly.

Here is a JSBIN with my issue: http://ift.tt/1MOVM41

Goal Route

import Ember from 'ember';

export default Ember.Route.extend({
  goal: '',
  actions: {
    nextStep: function() {
      console.log('Goto next step: ', this.get('goal'));
    }
  }
});

Template

<section>
  <div class="pod__content">
    Your Goal: {{goal}}
    {{input type="text" value=goal}}
  </div>
  <footer>
    <button {{action 'nextStep'}} class="btn btn--red">Next Step</button>
  </footer>
</section>




In Ember, can I yield input tag to component and not break my form?

I am thinking maybe I found a bug in EmberJS yield function.

What I want to achieve is, one component for forms, were I yield additional input tags, if they are needed. My example is more complicated, but I reproduced the "bug" in Ember Twiddle.

Basically, I have component:

form-component/template.hbs

<form {{action 'componentAction' on='submit'}}>
  {{yield}}
  <button type="submit">Submit</button>
</form>

And I want to yield input tag there

application/template.hbs

{{#form-component
  action="controllerAction"}}
  {{input value=name placeholder='Name'}}
{{/form-component}}

And as you can see, it doesn't work in the Twiddle. (It should update the text below the form to your input)

But if I move the input {{input value=name placeholder='Name'}} from application/template.hbs to component, it works:

UPDATED form-component/template.hbs

<form {{action 'componentAction' on='submit'}}>
  {{yield}}
  {{input value=name placeholder='Name'}}
  <button type="submit">Submit</button>
</form>

UPDATED application/template.hbs

{{#form-component
  action="controllerAction"}}
{{/form-component}}

Is it a bug, or am I missing something obvious here?




Ember pre-render: TypeError: 'undefined' is not a function (evaluating 'u.bind(e)')

I am trying to create a pre-render server for my ember app.

I installed ember-prerender (http://ift.tt/1RXQQgH), used the initializers provided in the /example, deployed it on one of my servers.

But when I try to launch it:

[Renderer 0] Engine starting up (phantom)
[Renderer 0] Restarting rendering engine in 25000 seconds after it failed
             with error: Phantom encountered an error: TypeError: 
             'undefined' is not a function (evaluating 'u.bind(e)') 

I'm unsure where to look. I tried:

  • Deleting all third-party SDK (Facebook, Google Analytics)
  • Logging different parts of the code (the event XContentReady seems to be fired)
  • Launching with the engine jsdom instead of phantom (gives: [Renderer 0] Restarting renderer, timed out while initializing)
  • Trying in production

I don't know where too look at now. The worse part is that I had it working a few days ago (see: Ember pre-render: timed out while initializing)




Ember cli adapter set custom path for type

Is it possible to set custom url for a specific type?

For example, this is my adapter definition:

/adapters/application.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    namespace: 'v1',
    defaultSerializer: 'JSONSerializer',
    host: 'http://api.example.com'
});

No what I want is to set a custom url for a specific adapter method. By default, each request will be sent to http://ift.tt/1jhNn0K} but for the store.query() method for example, I would like to tell ember to request http://ift.tt/1P5NhaD

Thank you




randomly failing acceptance-tests with Error: Assertion Failed: calling set on destroyed object

Some of my acceptance-tests (which involve actions) fail randomly when run with all other tests but never fail when I run them in isolation.

The Error: Assertion Failed: calling set on destroyed object is triggered in my action

I don't get any issue while using the table as a user so these issues only appear in tests. So I'm not sure if it's just because the app isn't destroyed correctly after each run.

Can I somehow see why the object is about to be destroyed or which observers are blocking it?

foos/index/route.js

startFoo(foos) {
  foos.forEach(function(foo) {
    foo.set('status', 'active');
    foo.save();
  });
},

This action gets passed down to a component (table) which shows a list of foo-models. Each row can be selected, doing so add the foo model of this row to a property selectedRows on this table component.

components/my-table/table.js

visibleColumns: Ember.A(),
selectedRows: Ember.A(),

selectRow(row) {
  let selectedRows = this.get('selectedRows');
  if (selectedRows.contains(row)) {
    selectedRows.removeObject(row);
  } else {
    selectedRows.addObject(row);
  }
},
isSelected(row) {
  return this.get('selectedRows').contains(row);
},

components/my-table/header/template.hbs

action.cb is the function startFoo

<button {{action action.cb table.selectedRows}}>
  {{im-icon icon=action.icon}}
</button>

The table component is pretty modular so it has header, columns, cells, rows and to share the state (like selected rows) I use an Ember.Object which is passed to all parts of the table component (which might be the issue?!!?)

components/my-table/row/component.js

isSelected: computed('table.selectedRows.[]', {
  get(/*key*/) {
    return this.get('table').isSelected(this.get('content'));
  },
  set(/*key, value*/) {
    this.get('table').selectRow(this.get('content'));
    return this.get('table').isSelected(this.get('content'));
  },
}),

components/my-table/row/template.hbs

content is a foo model

<td class="shrink">{{input type='checkbox' checked=isSelected}}</td>
{{#each table.visibleColumns as |column|}}
  {{my-table/cell content=content column=column}}
{{/each}}

Test

setup and teardown is ember-cli default

moduleForAcceptance('Acceptance | Foos');

test('click on action start changes state to active', function(assert) {
  server.create('foo', {
    status: 'paused'
  });

  // This is an ember-page-object
  fooPage
    .visit()
    .selectFoo()
    .clickStart();

  andThen(function() {
    assert.equal(fooPage.foos(1).status(), 'active', 'runs action');
  });
});




Ember-Simple-Auth: How to inject token in ajax request

sorry for that (maybe) silly question. Im super new to this topic!

I created a custom authorizer:

    import Ember from 'ember';
    import Base from 'ember-simple-auth/authorizers/base';
    export default Base.extend({
        authorize: function(jqXHR, requestOptions) {
            var accessToken = this.get('session.content.secure.token');
            if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
                jqXHR.setRequestHeader('Authorization', 'Bearer ' + accessToken);
            }
        }
    });

And now i want to include the token in a ajax request in my controller (this is my code without the token send):

// app/controllers/workouts.js
import Ember from 'ember';
import config from '../config/environment';

export default Ember.Controller.extend({
  requestEndpoint: config.ServerIp+'/workouts',
  workouts: function() {
        Ember.$.ajax({
            type: "GET",
            url: requestEndpoint
        }).success(function(data) {
            return data;
        })
  }.property()
});

Thank you very much for helping and understanding this great module!




Ember-cli-notifications not showing icons

i'm trying to use the Ember-cli-notifications in my new app, but the icon is not working at all.

Following the documentation, i need put this i n my configuration file:

  'ember-cli-notifications': {
    icons: 'bootstrap'
  }

And i already did.. but still, nothing happens and no error shows in my console or terminal.

Somethings this add-ons have poor documentation.. so, anyone who understand embers better them i do.. could answer me if i'm missing something?

Thanks.




Ember-notify giving error can't read property "Service" of undefined

I am using ember-notify ember-notify in my ember-cli project.

import {
  Component,
  inject
} from 'ember';
export default Component.extend({
  notify: inject.service('notify'),
  actions: {
    sayHello() {
      this.get('notify').info('Hello there!');
    }
  }
});

I just copied the same example code from documentation. But I am getting error 'cannot read property "service" of undefined' for line notify: inject.service('notify'), I've installed this addon and did a npm install as well.




Ember addon Vs normal package

I am trying to understand the differences between an Ember addon Vs normal package more from consuming side in my app.

So I would like to understand the following points;

  1. Differences in consuming both ? like what do we need to import, Brocfile changes, etc
  2. Is the installation process same for both ? Can both of them live in any repo or registry (like npm or bower registry)
  3. How do we decide whether to package something as addon Vs normal package (this is more from a developer perspective)?

You can also highlight any other significant differences.




lundi 23 novembre 2015

how to render a complete new template and leave the application template in ember

I am new to ember and javascript.I have designed a homepage(application.hbs).Now there is a option (About us) in application.hbs which should redirect to about us page(completely new).How should I leave the the homepage completely and move to about us page.Right now it is displaying the content of about us page below the homepage(application.hbs).

application.hbs(code snippet)

<section id = "FollowUs">
  <div class = "follow container-fluid">
    <div class="row section_blurb"> 
     <div class="col-xs-12 col-sm-4">
        <h1>example</h1>
        <a href ="#terms"><p>Home</p></a>
        <a href ="#terms"><p>Contact</p></a>
        <p>{{#link-to "aboutus"}}About Us{{/link-to}}</p>
      </div>
      <div class="col-xs-12 col-sm-4">
        <h1>Dolor Sit Amet </h1>
        <a href ="#terms"><p>Term & Conditions</p></a>
        <a href ="#privacy"><p>Privacy Policy</p></a>
        <a href ="#terms"><p>Lorem Ipsum</p></a>
      </div>
      <div class="col-xs-12 col-sm-4">
        <h1>Contact</h1>
        <p>99999999999</p>
        <a href ="#privacy"><p>hello@gmail.com</p></a>  
      </div>
      <div class="col-sm-6">
        <h1>Follow Us</h1>
        <div class = "row">
          <div class="col-xs-4 col-sm-2 col-sm-offset-2">
            <a href = "http://ift.tt/g8FRpY"> 
               <img src="images/ic_facebook yellow.svg" class="img-responsive"></a>
          </div>
          <div class="col-xs-4 col-sm-2 col-sm-offset-2">  
            <a href = "https://twitter.com/">
               <img src="images/ic_twitter yellow.svg" class ="img-responsive"></a>  
          </div>
          <div class="col-xs-4 col-sm-2 col-sm-offset-2">      
            <a href = "">
               <img src="../images/ic_google plus yellow.svg" class="img-responsive"></a>
          </div>
          <div class="col-xs-4 col-sm-2 col-sm-offset-2">     
            <a href = "#facebook">
               <img src="../images/ic_instagram yellow.svg" class="img-responsive"></a>
          </div>   
      </div>     
      </div>
      </div>
    </div>
</section>

router.js

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

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

Router.map(function() {
    this.route("aboutus");
});

export default Router;

aboutus.hbs

<p>hello</p>
{{outlet}}




How to manually load a GlimmerComponent (angle brackets component) in Ember?

I have small experiment where I use webpack for Ember development instead of ember-cli. I'd like to test the new GlimmerComponent (angle brackets component), but I can't get this to work. Here is my code.

I've included the Canary version of Ember and set the feature flag. The Ember.GlimmerComponent object is available. But the component will not be loaded/created, if I use it in my template. I can however use a normal {{my-component}}, if I place it manually on Ember.TEMPLATES. The templates are precompiled with require('components-ember/ember-template-compiler').precompile.

Note: Please no discussion about webpack vs. ember-cli. This is a personal research project and I probably learned more things about Ember with fiddling it into webpack by now as by reading the docs.




Cross origin requests not support in chrome in ember app (ubuntu)

How can i allow cross origin requests in ember, i am serving back-end in sailsjs , but i getting an error:

XMLHttpRequest cannot load localhost:1337/api/v1/project. Cross origin requests are only supported for protocol schemes: data, chrome, chrome-extension, chrome-extension-resource.

how to enable it in chrome in ubuntu.




Render Ember.JS on Umbraco

I have two websites on a IIS Server:

Umbraco:

http://ift.tt/1NaOjQp

Ember:

http://ift.tt/1leTG6l

I would like to render the Ember content on the following url:

http://ift.tt/1NaOlrH

Q1-Is there an easy way to do that? I've created an empty template and put my index.html, js files an css files on umbraco. However, the calls to my web api didn't work.

So I've configured IIS Reverse Proxy pointing to http://ift.tt/1leTG6l to do that. It's working, however when I try to open the umbraco admin panel, it's rendering my ember app.

Ps1: I can't open the umbraco admin page until I comment all the rewrite rules on web.config. Doing that, the requests to webapi stop working.

Ps2: /umbraco is in the umbracoReservedPaths variable at web.config

I thought it was a problem with the regular expression pattern. So I've tried several different regex, but I could not fix that.

Q2-Do I need to use IIS Reverse Proxy or should I use another tool / IIS feature to do that?

Q3-Is there any special config on umbraco?




Why does a component class needed to be reopened to specify positional params?

When specifying a positional param for a component class in ember, you have to reopen the class (like below) so it will work, you cannot include it in the initial declaration (at least from what I've seen of examples and my own experience).

import Ember from 'ember';

const component = Ember.Component.extend({ });

component.reopenClass({
  positionalParams: ['post'],
});

export default component;

If you do it in the single declaration (like below) it will not work

import Ember from 'ember';

export default Ember.Component.extend({
  positionalParams: ['post'],
});

Questions

  • Was this something overlooked in the design process? Or was this deliberate (maybe to discourage usage)?
  • Is this because it's a class attribute of some kind? Is there any way to specify class attributes in the class declaration?

It just feels gross that I can't make it part of the same expression and have to assign the class to a variable, reopen it, then finally export it.


Versions

  • ember.js @ 2.2



Ember controllers in nested routes

i'm very confuse about how ember controller works.

I'm starting with ember and ember-cli now, and i would like to understand more about how controller works.

If i have an nested route called new, inside a events resource, i should i have:

models/event
routes/events/new
templates/events/new

What about controllers?? I just work one simple controller, or should i use controllers/events/new too?

There isn't any generator command that will create every resource for me? I need call one by one?

Thanks.