samedi 31 décembre 2016

Is there a way to represent route closure actions instead of writing them all in the component shim?

I'm using ember-route-action-helper

I have a component shim that looks like this:

P.S. Not real action names

There are lots of actions that need to bubble to the route. I don't use controllers in my ember app.

This looks a bit clunky due to too many actions. Is there a way to represent this same information in another format or write it someplace else in my component .hbs file or .js file?




How does this JavaScript syntax bit from Ember.js work?

Going through the tutorial, I've encountered this:

this.render(hbs`
    
      <ul>
      
        <li class="city">
          
        </li>
      
      </ul>
    
  `);

I thought backticks represented a string? What is hbs then? Is it a function that is receiving handlbars snippet as an argument?




vendredi 30 décembre 2016

Reset Ember Component on Button Click

Background:

I have a component inside a template. This component is a pop up box which opens on a button click. This pop up box has check boxes (all by default set to false) inside of it. When I close this pop up box I want to completely reset all of the variables to the default settings, i.e. all checkboxes are now turned off. Currently, when I re-open this popup box the previous checkboxes are still checked. How do I do this without manually toggling every checkbox:

this.set("checkbox1", false);
this.set("checkbox2", false);
so on...

Is there a function that will automatically reset the component and set it back to false?




Ember's HTMLBars Compiler Error: Unexpected token export

I've inherited an Ember application at v1.8.1. I have successfully upgraded the application to v.1.9.1, and would like to continue to update it to at least v1.13.8.

In my v1.10.1 build, it appears that the ember-template-compiler is not quite meshing with Ember and am getting the following errors in the console:

Uncaught SyntaxError: Unexpected token export

Uncaught TypeError: Cannot read property 'name' of undefined

I'm looking for some direction in how to better track down the error, and what needs to be done to successfully upgrade.

The project is using broccoli (but not ember cli), so i'm trying to make the ember-cli-htmlbars plugin work.

Is there a better way to compile HTMLBars for Ember v1.10.1?

Should I transition the project over to Ember cli?

Please let me know what code you need would need to see.




Always reload model when entering a route

I have a route with a simple route handler that implements the model() hook.

export default Ember.Route.extend({
  model() {
    return this.store.queryRecord('some-model', {});
  }
});

I allow the user to transition to this route by clicking a link-to.

How can I force ember re-query for the record from my backend every time the user enters this route? (And not just the first time the user loads this particular route)




What a mistake when installing Electron?

When I try to install electron on Ubuntu 16.04 using

ubuntu 16.04 - node 6.9.2 - npm 3.10.9 - ember-cli: 2.10.0 -

ember install ember-electron

Installed packages for tooling via npm.
installing ember-electron
  identical config/environment.js
  identical electron.js
  identical tests/electron.js
  identical tests/package.json
Ember Electron requires configuration. Please consult the Readme to ensure that this addon works!
http://ift.tt/1mxKwmX
  install packages electron, electron-packager, electron-rebuild, ember-inspector, devtron
Refusing to install electron as a dependency of itself
Error: Refusing to install electron as a dependency of itself
    at checkSelf (/usr/lib/node_modules/ember-cli/node_modules/npm/lib/install/validate-args.js:53:14)
    at Array.<anonymous> (/usr/lib/node_modules/ember-cli/node_modules/npm/node_modules/slide/lib/bind-actor.js:15:8)
    at LOOP (/usr/lib/node_modules/ember-cli/node_modules/npm/node_modules/slide/lib/chain.js:15:14)
    at chain (/usr/lib/node_modules/ember-cli/node_modules/npm/node_modules/slide/lib/chain.js:20:5)
    at /usr/lib/node_modules/ember-cli/node_modules/npm/lib/install/validate-args.js:16:5
    at /usr/lib/node_modules/ember-cli/node_modules/npm/node_modules/slide/lib/async-map.js:52:35
    at Array.forEach (native)
    at /usr/lib/node_modules/ember-cli/node_modules/npm/node_modules/slide/lib/async-map.js:52:11
    at Array.forEach (native)
    at asyncMap (/usr/lib/node_modules/ember-cli/node_modules/npm/node_modules/slide/lib/async-map.js:51:8)




How To Update Hosted Firebase App

I would like to update my hosted firebase app.I have tried re deploying but it didn't work.I can't seem to find the answer on official firebase website either.How can we update hosted firebase apps ?

(Small toy ember app -> http://ift.tt/2iMSV7O )




Show boolean values in Handlebars

Trying to learn Ember JS, and I am a complete beginner.

I have an Ember JS application where a model has a boolean value. When I show this value in Handlebars, I do it like this:

YesNo

What I am not sure of is if this is the correct way to do it? Should I create a helper? Is there some other "best practice" way of doing this?

The model looks like this:

import DS from 'ember-data';
export default DS.Model.extend({
    id: DS.attr('integer'),
    name: DS.attr('string'),
    email: DS.attr('string'),
    location: DS.attr('string'),
    active: DS.attr('boolean'),
    administrator: DS.attr('boolean')
});

I am thankful for all the pointers I can get :)




Ember build in production environment is not loading addon's css file

I have an addon that I built myself which contains a single css file (addon/styles/<addon-name>.css).

When I use this addon on my Ember project and I do a build in development mode on that project everything works fine but when I do a production build the css file is not loaded.

Why is this happening? How can I use the css in my main app?




Add facet & value programmatically with VisualSearch.js in Ember JS

I'm using VisualSearch.js. Works great out of the box but my interface has a graph which shows the different statuses. When user clicks on one of the status I want to add a facet & value (i.e. status:open) to the search box and trigger the search.

I have two different components one contains graph and another contains visual search code.

How can I add facet from first component which contain graph?

**vsbase.js  #mixin** 

import Ember from 'ember'

export default Ember.Mixin.create({
init(){
    this._super(...arguments);
    this.set('role', this.get('rfpSession.currentUser.role'));
    if(this.globals.isSupplierUser(this.role)){
        this.set('validCampaignStates', this.globals.getCampaignStatusArray().getEach('id').toString());
    }
},
sendFilterAction: function(q){
    Ember.run.schedule('actions', this, function() {
        this.sendAction('gridFilter', q, this); //eslint-disable-line no-invalid-this
    });
},
sortByLabel: function(obj1, obj2){
    let name1 = obj1.label;
    let name2 = obj2.label;
    return name1.localeCompare(name2);
},
filterTypes: ['like', 'eq', 'gte', 'gt', 'lte', 'lt', 'not'],
prependFilterTypeOptions(filterTypes, searchTerm, ajaxMatches){
    if(filterTypes && Array.isArray(filterTypes) && searchTerm !== ''){
        filterTypes.forEach( type => {              
            let listItem = {value: searchTerm};
            switch( type ){
            case 'like' : {
                listItem.label = `Contains: "${searchTerm}"`;
                listItem.type  = type;
                break;
            }
            case 'gte' : {
                listItem.label = `>= "${searchTerm}"`;
                break;
            }
            case 'gt' : {
                listItem.label = `>  "${searchTerm}"`;
                break;
            }
            case 'lte' : {
                listItem.label = `<= "${searchTerm}"`;
                break;
            }
            case 'lt' : {
                listItem.label = `< "${searchTerm}"`;
                break;
            }
            case 'not' : {                  
                listItem.label = `Not "${searchTerm}"`;
                break;
            }
            default : {
                break;
            } 
            }
            ajaxMatches.unshift(listItem);
        });
    }
},
getResult(rowAttr, column){
    let result = {type : 'eq'};
    switch(column){
    case 'Makegoods': {
        result.label = rowAttr ? 'Yes' : 'No';  
        result.value = rowAttr.toString();  
        break;
    }       
    default: {
        result.label = rowAttr;
        result.value = rowAttr;  
        break;
    }
    }
    return result;      
},
vsQueryToDbFilter(facetModels, columns){
    console.log('vsQueryToDbFilter');
    //GM - START helper functions used further down
    let labelToFilterField = function(label){
        console.log('label -' + label);
        let filterField;
        columns.find((col) => {
            if(col.label === label){
                if(col.include){
                    filterField = `${col.include}.${col.column}`;
                } else {
                    filterField = col.column;
                }                   
                return true;
            }
            return false;
        });
        console.log('filterField -- '+filterField);
        return filterField;
    };
    //GM - END helper functions

    let dbFilters = {};
        console.log('facetModels.length -- '+facetModels.length);
    if( facetModels.length){            
        facetModels.forEach(function(vsFilter){
            let columnLabel = vsFilter.attributes.category;
            let filterField = labelToFilterField(columnLabel);
            let filterKey = (vsFilter.attributes.filterVal).replace(',', '\\,');
            let filterType = vsFilter.attributes.filterType;

            if(filterType !== 'eq'){                    
                if(!dbFilters[filterType]){
                    dbFilters[filterType] = {};
                }
                if(!dbFilters[filterType][filterField]){
                    dbFilters[filterType][filterField] = filterKey;
                } else {
                    dbFilters[filterType][filterField] = dbFilters[filterType][filterField] + ',' + filterKey;
                }
            //GM filter[col]
            } else { //this will be a regular equvilence filter
                if(!dbFilters[filterField]){
                    dbFilters[filterField] = filterKey;
                } else {
                    dbFilters[filterField] = dbFilters[filterField] + ',' + filterKey;
                }

            }   
        }, this);           
    }
    console.log('dbFilters -- ' )
    console.dir(dbFilters);     
    return dbFilters;   
}
});

visual-search.js #component

import Ember from 'ember';
import moment from 'moment';
import VSBaseMixin from 'rfp-client/mixins/vs-base';
const _0 = 0;
const _1 = 1;

export default Ember.Component.extend(VSBaseMixin, {
    ajax: Ember.inject.service(),
columnNames: [],
complexResults: false,
containsDropdownItem(results, newItem){
    for(let i = _0; i < results.length; i++){           
        if(results[i].label === newItem.label){
            return true;
        }
    }
    return false;
},
didInsertElement: function () {
    let self = this;

    Ember.run.scheduleOnce('afterRender', this, function() {            
        var visualSearch = VS.init({
            context: this, 
            container: self.$('#' + self.get('vsID')),
            query: '',
            preserveOrder: true,                
            showFacets: true,
            callbacks: {
                search: function(query, searchCollection) {
                    let dbFilter = self.vsQueryToDbFilter(searchCollection.models, self.get('columns'));
                    self.sendFilterAction(dbFilter);  
                },
                facetMatches: function(callback) { //fired when user first interacts with filters
                    let cols = self.get('columns').map(function(value) {                            
                        return value.label;                         
                    });
                    callback(cols);

                },
                valueMatches: function(facet, searchTerm, callback) {  //fired when user selects a column to filter
                    this.gridData = self.get('vsData'); 
                    self.get('columns').find((column) => {

                        this.matchTerm = column.label;

                        if(this.matchTerm === facet){

                            let dropdownResults = [];
                            this.gridData.forEach(function(instance){
                                let dropdownItem = instance.get(column.column);
                                let dropdownResult = self.getResult(dropdownItem, this.matchTerm);
                                if(!self.containsDropdownItem(dropdownResults, dropdownResult)){                                                                                
                                    dropdownResults.push(dropdownResult);                                       
                                }
                            }, this);
                            dropdownResults.sort(self.sortByLabel);
                            self.prependFilterTypeOptions(column.filterTypes, searchTerm, dropdownResults);
                            callback(dropdownResults, {preserveMatches: false});
                            return true;

                        } else { //eslint-disable-line no-else-return
                            return false;
                        }
                    }, this);

                }
            }
        });

    });
}
});




Ember server port permission

When doing ember s on any ember app, I get:

Serving on http://localhost:4200/
Livereload failed on http://localhost:49152.  It is either in use or you do not have permission.

Checking the failing port with lsof -iTCP:49152 shows nothing. So I guess this must be a permission issue. I installed this on a new Mac using the setup suggested at http://ift.tt/2ioObVn: brew install nvm, then nvm install 6.9.2, then npm install -g npm@latest.

I can start the server by using sudo ember s. But I can also start the server by explicitly assigning a different port for livereload – which doesn't make any sense given that nothing is blocking port 49152…

  • nodejs 6.9.2
  • nvm 0.32.1
  • npm 3.10.9
  • ember-cli 2.10.0

I'm confused as to what the exact cause of this problem is and how I can solve it. Any hints appreciated.




jeudi 29 décembre 2016

How can I set a property inside route deactivate to use inside controller?

I have a ember route as follows which uses deactivate function to set some properties when route deactivation.

   export default Ember.Route.extend({
       deactivate: function() {
        this._super();
        this.set('scrollSelector',mainContainer);
      // need to set property here and use it inside controller
    }
    });

How can I set property inside deactivate method to be used inside controller level. ? Appreciate any help.




Clearing form fields in Ember 2.10

I'm following a tutorial on building an ember 2.10 app. I've moved my validation logic out of my contact controller and placed it inside my contact model. I've placed my action (saveContact) in my contact routes file. I can save my new contact to Firebase database without error. I'm stuck on how to clear out my form.

My contact route file looks like

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return this.store.createRecord('contact');
  },

  actions: {

    saveContact(newContact) {
      newContact.save().then((response) => {
        const email = this.get('model.email');
        const message = this.get('model.message')
        this.set('email', '');
        this.set('message', '');
      })
    }

  }

});

I'm trying to retrieve the current value in the form and set both message and email to empty strings.

I've run a test and console logged email to the console and it return undefined.

In the input fields, the value being passed in are model.email and model.message.

Has anyone else been stuck on this problem?




Controller parent sharing content between its child

I have a base class which has some properties. I'm inheriting this class into two other controllers. Whenever I set a content to this variable, though, the content is shared between the two controllers. I don't this to happen, otherwise I'd have used Mixins. I want to set the content in one child to something and when I go to the other route, the content is still blank.

// base controller
export default Ember.Controller.extend({
    method: null,
    actions: {
        changeMethod() {
            this.set('method', 'content is shared');
        }
    }
}
// children.js
import BaseClass from './base-class';

export default BaseClass.extend({ //code here });

// child1.hbs
 - it shows the same as child2.hbs

// child2.hbs
 - it shows the same as child1.hbs




Using .bind() in function does not work [duplicate]

This question already has an answer here:

I have the follow statement in one controller which is inheriting another one:

this.actions.changePageSize(page_size).bind(this);

And in the parent controller I have this

actions: {
    changePageSize(page) {
        this.set('page_size', page);
    },

I get the error

TypeError: this.set is not a function

If I pass this as an argument and use its alias, it works. Like this:

 this.actions.changePageSize(this, page_size);

 actions: {
    changePageSize(_this, page) {
        _this.set('page_size', page);
    },




How to parse consuming applications models?

I'm attempting to create an ember add-on that parses the consuming applications models and creates files based on them. I have found docs on how to create files, but nothing on parsing the consuming application, storing and creating etc.. How might I parse the consuming applications files or models? Either an answer or links to docs would be awesome.




mercredi 28 décembre 2016

Create base class for controller to extend in Ember application

I'm trying to create a Base Class for my controllers, so I can avoid duplication of code.

The problem here is that it is throwing me errors whenever I try to use it.

"Assertion Failed: You attempted to define a but did not pass the parameters required for generating its dynamic segments. Could not find module controllers/base-inventory imported from frontend/controllers/inventory"

To create my base controller I am using ember cli and this is what I did:

ember g controller base-inventory

Then

// base-inventory.js
const BaseInventory = Ember.Controller.extend({
   //my code...
});
export default BaseInventory;

In the controller where I want to use this base class I did the following

import BaseInventory from 'controllers/base-inventory';
// also tried import { BaseInventory } from 'controllers/base-inventory';
// and  export default new BaseInventory({});
export default BaseInventory.extend({
    //more code here...
});

Any thoughts of what I am doing wrong? I didn't plan to use mixins, because it doesn't seem the best option here, but if it's not possible to do the way I'm trying to, I'll write a mixin.




Ember array option with ember power select

My model has 2 attributes (baseCurrency and otherCurrencies) whose values are selected in a form by 2 ember power selects dropdown menu whose options depend on 2 computed properties (baseCurrencyOptions and otherCurrencyOptions)

controller

  ...
  otherCurrencyOptions: Ember.computed('model.baseCurrency', function() {
    console.log(`allCurrencies changed to: ${this.get('allCurrencies')}`);
    return Ember.A(this.get('allCurrencies')).removeObject(this.get('model.baseCurrency'));
  }),
  baseCurrencyOptions: Ember.computed('model.otherCurrencies', function() {
    console.log(`allCurrencies changed to: ${this.get('allCurrencies')}`);
    return Ember.A(this.get('allCurrencies')).removeObjects(this.get('model.otherCurrencies'));
  }),
  actions: {
    addOtherCurrency(currency) {
      this.get('model.otherCurrencies').pushObject(currency);
    },
    selectCurrency(currency) {
      this.set('model.baseCurrency',currency);
    },
  ...

allCurrencies property contains a list of all currencies and it is not supposed to change over time.

template


  


  


Problem is that every time I select a currency in one or the other of both dropdown menus allCurrencies property gets updated loosing in an irreversibile manner every selected currency. Moreover I got the following warning:

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




Not able to copy from my application

I have my web application written in EmberJS. I am able to copy the text in 'input' fields , but not able to copy those in 'labels' , 'h1' such kind of fields in any of the browsers.

Any special handling needs to be done for those to make them enable for copy?

Any help much appreciated.Thanks.




this.set is not a function error

Inside my controller I have this code to fade out a div:

popUpFadeOut: function(){
if(this.get('bid.popUpContainerOpacity') === 0){
this.set('bid.popUpContainerOpacity', 1);
this.set('bid.popUpContainerDisplay', 'block');   
setTimeout(this.fading, 1000); //popup box fades away after 1 seconds
}
},

fading: function() {
    this.set('bid.popUpContainerOpacity', 'bid.popUpContainerOpacity' - 0.1);

    if (this.get('bid.popUpContainerOpacity') <= 0)
    {
       this.set('bid.popUpContainerOpacity', 0);
       this.set('bid.popUpContainerDisplay', 'none');
    }
    else
    { 
       requestAnimationFrame(this.fading);
    }
},

Inside the fading function, I get this error:

Uncaught TypeError: this.set is not a function(…)

While I'm not an expert on the 'this' keyword, my guess is that it cannot find the function because fading gets called inside popUpFadeout, so calling this.set in fading will look for a set method inside popUpFadeOut, which does not exist.

My question is: How do I get access to the set method of my controller inside fading?




mardi 27 décembre 2016

What is the correct syntax for the each helper

In my controller, I have an array called bidderArrayText inside a bid object, so bid.bidderArrayText.

In my template, I want to display each item of the array, but I'm not sure how. This is what I have, but it does not work:


<p>. </p>

<p>Be the first to bid!</p>


What is the correct syntax? Thanks.




How to include something from NPM with aliasing in your Ember CLI build?

I'm trying to include an NPM package (this one), that has a dependency that needs aliasing to get the browser version (as described here) in my ember-cli build. In the official documentation, it's not really clear how this can be done.

Ideally, this would be something like this:

app.import('joi-browser', { alias: 'joi' });
app.import('edzif-validation');

But that does not work. Does anyone have a clue on how to coax the ember-cli/broccoli setup to do this?




Ember.js passing 'each' variable into component

In my Ember app, I'm trying to make a view-picks-row component for each item in my array picks. It looks like this:


  


I'm getting the following error:

Error: Parse error on line 26:
...ew-picks-row player=playerPicks, incorre
-----------------------^
Expecting 'OPEN_SEXPR', 'ID', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'INVALID'

Am I not allowed to pass each variables into a component? What would be the preferred way to do what I am trying to accomplish?

Thanks!




lundi 26 décembre 2016

this.get in controller is 'not a function'

I'm trying to set the style of an html element and I read that I have to do it this way:

bid: {
popUpContainerDisplay: "none",
popUpDisplay: Ember.computed('bid.popUpContainerDisplay', function() {
       return Ember.String.htmlSafe("display: " + this.get('bid.popUpContainerDisplay'));
   })
},

then in my hbs file, I write

<div id="popUpContainer" style=>

However, this is giving me some errors:

jQuery.Deferred exception: this.get is not a function TypeError: this.get is not a function
at Object.<anonymous> (http://localhost:4200/assets/auction-ember.js:53:77)
at ComputedPropertyPrototype.get (http://localhost:4200/assets/vendor.js:26852:28)
at Object.get (http://localhost:4200/assets/vendor.js:31759:19)
at NestedPropertyReference.compute (http://localhost:4200/assets/vendor.js:24910:28)
at NestedPropertyReference.value (http://localhost:4200/assets/vendor.js:24720:45)
at ReferenceCache.initialize (http://localhost:4200/assets/vendor.js:55111:52)
at ReferenceCache.peek (http://localhost:4200/assets/vendor.js:55085:29)
at DynamicAttribute.flush (http://localhost:4200/assets/vendor.js:58752:35)
at SimpleElementOperations.addAttribute (http://localhost:4200/assets/vendor.js:58414:36)
at SimpleElementOperations.addDynamicAttribute (http://localhost:4200/assets/vendor.js:58374:22) undefinedjQuery.Deferred.exceptionHook @ jquery.js:3846process @ jquery.js:3642

jquery.js:3855Uncaught TypeError: this.get is not a function(…)

What am I doing wrong? Thanks.




REST API call with Ember js

How to use any rest api(json) in Ember templates(hbs). I have a service deployed on apache tomcat and I want to use its response in ember js. I tried all the things available online but no luck.

Below is my code snippets;

-----------app\adaptors\application.js--------------------
    import DS from 'ember-data';
    import Ember from 'ember';

    var App = window.App = Ember.Application.extend();

    App.UserAdapter = DS.RESTAdapter.extend({
      find: function(){
          return Ember.$.getJSON('http://localhost:8082/emberTestService');
        }
    });
--------------routes\user.js----------------------
    import Ember from 'ember';

    var App = window.App = Ember.Application.extend();

    App.UserRoute = Ember.Route.extend({

      model: function(){
        var adapter = App.UserAdapter.create();
        return adapter.find();
      }
    });
-------------templates\application.hbs---------------
    <h1>Welcome in app</h1>
    
    

Service http://localhost:8082/emberTestService returns { "name": "Tomcat" } and I want this response to return on my template.

Thanks in advance.




dimanche 25 décembre 2016

How to toggle between links in ember js?

enter image description here

Hi, i am new to ember js. Can someone please help me with my code? I have created this but i don't know how can i give action to each links. When i click on BreakFast, it should only show me 3 search box(BreadType, cheeseType and meatType) only and other should hide. same for Lunch and Drinks. i have also created route for menu in router.

--------------/////application.hbs

<h1>Welcome!!</h1>
     BreakFast
     Lunch
     Drinks
    

-------------/////menu.hbs

<div>
        <p>Hello from BreakFast</p>
        <label>
            Bread Type:
            Cheese Type:
            Meat Type:
        </label>
    </div>
<div>
    <p>Hello from Lunch</p>
    <label>
        Calories:
        Price:
        Veg/Non-veg:
        <select>
            <option>V</option>
            <option>N</option>
        </select>
    </label>
</div>
<div>
    <p>Hello from Drinks</p>
    <label>
        Drink Name:
        Price :
        Ice: <select><option>Y</option>
                     <option>N</option>
            </select>
    </label>
</div>




How to access the correct `this` inside a callback for AJAX call?

I am unable to access 'this' in callback function but i end up using 'this' pointing to AJAX object rather than 'this' object who invoked onClickEmail function. I tried getting the reference in 'that' variable but that didn't helped much either. Anything I am doing wrong here:

onClickEmail(){
    var that = this;
    $.ajax({
            url: 'http://ift.tt/2i4O5zw'
        }).then(function(response) {
            hey = that;
        });
}




samedi 24 décembre 2016

Where do I put my WebSocket code and how to pass its data to a template

I have a small application that I want to try to implement using Ember.js, but I'm not really sure what the best way to do it is.

The application is just supposed to take bids from a user and when a countdown reaches 0, it prints out that the highest bidder has won.

I'm wondering where to put the code for my WebSocket that receives data from a server and how to pass the data received to the template. I read that the data should be passed in the route's model, but I'm not sure how.

Right now I actually have implemented most of it, but most of the html is just put into my index.hbs file, and then I do all the logic with the websockets and changing the values of the html elements inside a script tag also in index.hbs. This just feels like a terrible way to do it, so I would like to know how to utilize some of the features of Ember.js to improve it.




Use greensock with handlebars

I have a template I made with Handlebars that looks like this:

 <script type="text/x-handlebars-template" id="student-template">
       
          <div class="clearfix">
            
              <div class="col-lg-3 col-md-4 col-xs-6 thumb">
                <img src="" title=" /> 
                </div>
           </div>  
       
    </script>

I would like to use Greensock library to animate the rendering of student images. From my understanding about greensock, My code would like like this:

var timeline = new TimelineLite();
timelime.add(TweenLite.from($currentImage, 1, {y: 100}));
timelime.add(TweenLite.from($nextImage, 1, {y: 100}));
timelime.add(TweenLite.from($nextnextImage, 1, {y: 100}));
.. and so on for all images..

How do I render images based on my template and at the same time loop through all images to animate them?




EmberJs Data Goes Null to Server

I am building a toy app and wanted to work with a simple 1:many relationship. My car model "hasMany comments" & my comments "belongsTo car".I want a comment to be created from cars/car route.So i didn't created a route for comments/new.For a quick trial i have added a button that has "saveComment" action.

<button type="submit" >Submit</button>

!!! I am passing the model(which refers to current Car object) because in my action i want to read it's id and set it to comments car_id.

And here is the correspanding route file

  model(params){
   return this.store.findRecord('car', params.car_id);
  },
 actions: {
  saveComment(model){
     let car = this.store.peekRecord('car', model.id),
     let newComment = this.store.createRecord('comment'{
            car: car,
            body: 'Some filler text! ',
        });
   car.get('comments').pushObject('newComment');
   newComment.save();
  }

The problem is, my (let the route be cars/10) current template includes the newly generated comment with the proper body, however when i inspect it, belongsTo relationship looks empty.Since car_id goes null, after a reload, new generated comments disappeares.(not from the database tho, it is saved succesfully without a car relationship).What should i do to get this comments.car saved? TIA




vendredi 23 décembre 2016

EmberJS access Ember.Object in Ember.Controller

My purpose is to seperate a lot of boilerplate code in an Object, but i know how do access this Object in my Controller.

The Code looks like this.

import Ember from 'ember';
"use strict";

var panel = Ember.Object.extend({

});
const Person = Ember.Object.extend({
    init() {
        this.set('shoppingList', ['eggs', 'cheese']);
    }
});


export default Ember.Controller.extend({
    width: 0,
    height: 0,
    panel: null,




How does EmberJS deal with different output between findRecord() & findAll()?

Let's say I have a simple model my-data:

export default Model.extend({
  foo: attr(),
  bar: attr()
});

Let's also say my backend is setup so when I use findAll() which calls /api/v1/my-data/, the response only returns the foo attribute, but if I use findRecord() -- eg, /api/v1/my-data/5 --, the response contains both foo and bar.

Is EmberJS smart enough to merge these two responses without overwriting any attribute that's not in the response? In other words, if I first do a findRecord('my-data', 5), then both foo & bar will be set, but if I subsequently call findAll(), which will also contain record 5, can I expect the record with id 5 to still have both foo and bar set, or will findAll() completely overwrite record 5 with bar becoming unset or NULL?




How to connect Rails collection route to Ember JSON API Adapter?

I have a Rails resource like this...

resources :listings do
  collection do
    get :stats
  end
  ...
end

such that GETting /listings/stats?various_params gives me a JSON API compliant response with statistics about the Listing model according to the parameters I provide.

In my Ember frontend, also using the JSON API Adapter, I would like to be able to something like this:

model() {
  return this.store.query('listing/stats', {startdate: startDate.toISOString, otherparams: etCetera});
}

What's the "Ember Way" to accomplish this, if any? I would like to avoid hacking the JSON API Adapter as much as possible, and it's my understanding that custom methods defined on an Ember model's file are mostly for interacting with a specific record (i.e., /listings/:id/whatever)

Thanks




EmberJS Cannot read property 'on' of undefined

I saw a lot of topics by this problem but I couldn't find the right one. I'm trying to create hangman game and this is my code of letters component. I can't see my problems..

import Ember from 'ember';

export default Ember.Component.extend({

  game: null,
  letter: null,

  isMissed: false,
  isGuessed: false,

  init() {
    this._super.apply(this, arguments);
    var game = this.get('game');

    game.on('didGuessLetter', (l) => {
      if (l === this.get('letter')) {
        this.set('isGuessed', true);
      }
    });
    game.on('didMissLetter', (l) => {
      if (l === this.get('letter')) {
        this.set('isMissed', true);
      }
    });
    game.on('didReset', this, this.reset);

  },

  reset() {
    this.set('isMissed', false);
    this.set('isGuessed', false);
  },

  click() {
    if (!(this.get('isMissed') || this.get('isGuessed'))) {
      this.get('game').playLetter(this.get('letter'));
    }
  }

});

I get error: error in console

I couldn't find the bad place..




Unclosed element

I'm getting this error:

Error: Unclosed element `container.style.display` (on line 25). 

Line 25 of my program is:

if ((container.style.opacity -= .01) <= 0)

But I think it's referring to the line below:

container.style.display = "none";

Why am I getting this error?

The context:

<script>
var container = document.getElementById('popUpContainer');

function popUpFadeOut() {
    if (container.style.opacity == 0) {
        container.style.opacity = 1;
        container.style.display = "block";

        var fading = function fade() {

            if ((container.style.opacity -= .01) <= 0) {
                container.style.display = "none";
                container.style.opacity = 0;
            } else {
                requestAnimationFrame(fade);
            }
        };

        setTimeout(fading, 1000); //popup box fades away after 1 seconds
    }
};
</script>




MacOS HelpViewer navigation buttons doesn't work for web SPA content

Recently we had to migrate embedded help for Mac product to web and have referenced it from Mac HelpViewer. As far as I know MacOs HelpViewer is a custom made webkit based applilcation that is used to display product help, which has to be presented in a specifis folder structure. HelpViewer's nav and menu buttons aren't similiar to any browsers buttons, and for the rest browsers our web help works perfectly fine in SPA mode with

window.history.pushState

But once this SPA behaviour is applied to HelpViewer navigations buttons don't react (they are disabled) to changing url or adding state to window.history collection. MacOS nativa applications also have web based help, e.g: calendar app. This help is based on Ember.js and has some SPA behaviour also, but this one trigger HelpViewer's buttons to react (they become enabled) and work once clicked.

The problem I try to solve is how to trigger HelpViewer to react on changing url or window.history. Maybe ember.js does some stuff except for adding




Ember unknown injection ajax

i'm using ajax in my ember app as follows (component):

ajax: Ember.inject.service(),

  ajaxRequest(method, href, type, json,callback) {
    let ajax = this.get('ajax');
    let promise = ajax.request(href, {
      method: 'POST',
      data:  json
    });
    promise.then(() => {
     callback();
    }).catch((e) => {
     console.log(e);
   });},

But i get :

ember.debug.js:2307 Uncaught Error: Attempting to inject an unknown injection: 'service:api'

DEBUG: 
-------------------------------
Ember      : 2.9.1
Ember Data : 2.10.0
jQuery     : 3.1.1
-------------------------------




jeudi 22 décembre 2016

Which is better between Ember statement vs HTML statement in Ember?

I'm new in Ember.

As I know, the Ember is consist of [.js/.hbs(handlebars)].

when I search the component in the google, I got 2 kinds of source.

1st is like 'HTML' <input type="checkbox" class="btn btn-success active" />CheckBox01<br />

and 2nd is like more 'Ember'. CheckBox02

but I think these are same.. so I don't select what I use.

Frankly I want to follow 2nd style, but when I try it('http://ift.tt/1WhnMVM'), I got failed.
so I just use 1st style these days. and It is more easy to me because I used to handle HTML.

Anyway, the question is what are the different between Ember Style and HTML Style.

Thanks.




Ember.js 2.7 - How to check validation on an input field?

I'm pretty new to Ember.js and I'm having trouble how to do a validation on a certain input field.

Here is the code for my template index.hbs:

<div class="jumbotron text-center">
  <h1>Coming Soon</h1>

  <br/><br/>

  <p>Don't miss our launch date, request an invitation now.</p>

  <div class="form-horizontal form-group form-group-lg row">
    <div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-1 col-md-5 col-md-offset-2">
      
    </div>
    <div class="col-xs-10 col-xs-offset-1 col-sm-offset-0 col-sm-4 col-md-3">
        <button disabled=  class="btn btn-primary btn-lg btn-block">Request invitation</button>
    </div>
  </div>
  
    <div class="alert alert-success"></div>
  
  <br/><br/>
</div>

and here is the code from my controller index.js:

import Ember from 'ember';

export default Ember.Controller.extend({

  headerMessage: 'Coming soon',
  responseMessage: '',
  email: '',

  isValid: Ember.computed.match('email', /^.+@.+\..+$/),
  isDisabled: Ember.computed.not('isValid'),
});

The input field that I want to get validation for is the email one. I know how to go about the validation by replacing the value="" field to just value="email", but I want to know how I can do it using the value=model.email

This seems like an easy problem, but I can't find anything on the docs about this particular issue.




Prevent removal of Ember.deprecate in production

My goal is to log deprecation warnings to a server so they can be tracked. The code for this is already built by hooking into registerDeprecationHandler. The thought was that by doing this, we coudl essentially crowd source our deprecation warnings so it is easier to resolve them later. However, this does not end up working in production.

In Ember docs for Ember.deprecate it states:

In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build.

Is there any way to prevent Ember from removing Ember.deprecate from the production build? I feel like there ought to be an environment setting or something that controls this.. I was surprised that Ember was doing this at all because it seems like something that should be an opt-in feature.




Ember JsonApi with Jax-Rs content type on Posts

I am using Ember-Data clientside and Tomee7 with Jax-RS on the Server.

I would very much like use the Ember-Data's JsonAPIAdapter and adhere to the jsonAPI specifications

If I understand correctly, all HTTP communications must have the Content-Type header set to application/vnd.api+json

The Problem when I try to POST something to the Server I get a 415 Unsupported Media error

I've decorated my services like this:

@POST
@Consumes("application/vnd.api+json")
@Path("somePostEndPoint")
public Response postService (@FormParam "someData" String someData) {
        //....
}

but I am returned:

An application/x-www-form-urlencoded form request is expected but the request media type is application/vnd.api+json. Consider removing @FormParam annotations

When I make the Request outside of EmberData (with Postman) Everything works fine.

I understand the @FormParam requires Content-Type: application/x-www-form-urlencoded. Could I use something else?

It would be a shame to not get to use the JsonApiAdapter. :(

does anyone have any Ideas what I could try?

Thanks!




can i createRecord() without using save()?

I'm learning ember from the scratch and i stumbled upon something i can't quite understand:

const newNote = this.store.createRecord('note', {
    content: 'once upon a time...',
});

newNote.save().then(this._redirectToNewNote.bind(this));

Is the result of createRecord in the database before saving, or is it like a dummy object? can I use createRecord without saving?




Disable application.hbs for a single route in Ember.JS

Simply, the web app needs to use the application.hbs template 99% of the time but for a single route, I would like to disable it and render only the route template.

Like 'Layout=null;' in asp.net

Thanks in advance.




how to write nested if in ember htmlBars

how to write nested if conditition in ember htmlBars

<div >

below is ember verison

DEBUG: Ember : 1.13.0
Ember Data : 1.13.7
jQuery     : 1.11.1




mercredi 21 décembre 2016

How to ensure Ember Data remove the cache from store?

Pretty sure it's just some noob mistake I made, I've got a controller that shows the model count

const BlahController = Ember.Controller.extend({
    totalRows: Ember.computed('model.[]', function() {
        let items = this.get('model') || [];
        return items.get('length');
    }),
    ...
})

then when I delete the model I do it using destroyRecord and even ensure that it's unloaded

model.destroyRecord().then(() => {
    this.get('store').unloadRecord(model);
}

Any idea why totalRows is never updated? I would've thought that by calling store.unloadRecord it will actually remove the model from the store and updates the model array in the controller?




ember broccoli foundation-sites

When try to ember build or ember serve I get next error:

The Broccoli Plugin: [SourceMapConcat: Concat: Vendor /assets/vendor.js] failed with:

Error: ENOENT: no such file or directory, stat '/Users/artem_shevtsov/DATA/Projects/laser/ui/tmp/source_map_concat-input_base_path-TNdPSywn.tmp/bower_components/foundation-sites/dist/foundation.js' at Object.fs.statSync (fs.js:906:18) at FSMonitor._measure (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/heimdalljs-fs-monitor/index.js:66:21) at Object.statSync (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/heimdalljs-fs-monitor/index.js:82:30) at Concat.keyForFile (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/broccoli-caching-writer/index.js:87:20) at Array.map (native) at Concat.CachingWriter._conditionalBuild (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/broccoli-caching-writer/index.js:109:65) at /Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/broccoli-plugin/read_compat.js:93:34 at tryCatch (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/rsvp/dist/rsvp.js:538:12) at invokeCallback (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/rsvp/dist/rsvp.js:553:13) at publish (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/rsvp/dist/rsvp.js:521:7) at flush (/Users/artem_shevtsov/DATA/Projects/laser/ui/node_modules/rsvp/dist/rsvp.js:2373:5) at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9)

I tried npm and bower cache clean, rm -rf tmp node_modules bower_components and plugins reinstallation

Also tried manual installation with npm and bower (npm i foundation-sites, bower install foundation-sites) and add

app.import('node_modules/foundation-sites/dist/js/foundation.js')
app.import('node_modules/foundation-sites/dist/js/foundation.min.js')

(or bower_components/... respectively) but it does not work

❯ npm -v
3.10.9

❯ node -v
v7.2.0

❯ ember -v
v7.2.0 ember-cli: 2.9.0 node: 7.2.0 os: darwin x64




You must provide a string key when calling `yieldItem`; you provided undefined

After upgrading ember 1.8.0 to ember 1.13.3 getting mention error.

can any one please tell me why this error and what is meant by that.




mirage ember attributes are undefined

I'd like to use mirage with ember to simulate my api backend. I've followed the quick start and can get 10 entries via a call to the store:

return this.get('store').findAll('authors')

I've using createList to set this up, but when I view them only the id and type are correct. I can see the attribute names in ember chrome add on but everything is undefined.

Any idea what I'm doing wrong?

I thought it might be something to do with the serialiser which is:

import { JSONAPISerializer } from 'ember-cli-mirage';

export default JSONAPISerializer.extend({
});

I believe the attributes are normally in the data attribute and that is handled by ember data so it shouldn't need any further changes right?

Thanks!




How to profile ember-cli application?

I have found extension ember-renderspeed to profile templates rendering

But I would like to have some additional profiling for:

  • time of parsing models for Ember store
  • Ember store profiling
  • routing profiling

Does someone know any existed extension/solution for that cases?

thanks




Ember data model recordArray toArray issue

I use ember 2.9.1 and ember data 2.9.0.

I have a simple model say 'users' which has 'name' and 'address' fields. When i query the model using findAll('user'), the data from server is right. But when i try to get the actual data(using toArray) from the recordArray returned, the data i get array of classes.

i.e., if i have two users, then i get an array of classes instead of the actual data i expect like([{name:"user1", address: "address1"},{name:"user2", address: "address2"}]) to give to the template.

Am i doing it right?




mardi 20 décembre 2016

Ember.js can't mock ajax using jquery-mockjax

I use jquery-mockjax to mock my AJAX request for my tests and after I upgraded my ember from 2.3.0 -> 2.10.0 it no longer works because my service is using Ember.$.ajax() instead of directly $.ajax()

any idea how to make mockjax still work with Ember.$.ajax()? Or shall I just replace all Ember.$.ajax() instance to $.ajax()? Is this the only way?




emberjs mock-server adapters api

I am using http-mock server to display some data in my project. The mock server is named books.js and it has following:

var books= [
{
  id: 1,
  title: 'Good',
  description: "This is good"
},
{
  id: 2,
  title: 'Bad',
  description: "This is bad"
},
];

booksRouter.get('/', function(req, res) {
res.send({
  'books': books
 });
});

I have a model named 'book' which has:

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr(),
    description: DS.attr()
});

My adapters have:

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    namespace: 'api'
});

And my routes is named books.js and have the following code:

import Ember from 'ember';

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

Everything seems correct but when I try to load the link localhost:4200/books (which is the right route) I get this error:

GET xhr localhost:4200/api/book  404 not found
Error while processing route: books    Ember Data Request GET  /api/book returned 404

The api is displayed when I check localhost:4200/api/books. What I need here is to point to /api/books and not /api/book

What is causing this error? and what might be the solution for this? I would appreciate any help that would help me resolve this issue. I am stuck in the project because of this and could not find help anywhere else. I am using ember version 2.10.0.




Why doesn't ember-cli see my vendor file

I have an external javascript file that I've placed in vendor/. In my ember-cli-build.js file, I import the script:

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

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

  app.import('vendor/myscript.js')

  return app.toTree()
}

When I run the app I get this warning: Warning: ignoring input sourcemap for vendor/myscript.js because ENOENT: no such file or directory, open '/path/to/project/root/tmp/source_map_concat-input_base_path-http://ift.tt/2hF4pbZ'

Why is it searching for the script in /tmp?




Is there an importable function to convert a javascript object to a query string?

Is there a function I can import for converting a plain javascript hash/object into a query string?

So, here are the requirements:

  • Cannot be based on jQuery (I need fastboot support)
  • Must support nested objects & arrays.
  • Must be built into Ember framework (no plugins)

I'm not really wanting to have another plugin dependency, since I know this is done internally in Ember.




Ember acceptance test andThen() doesn't wait until scroll events are complete

I need an emberJs acceptance test to be able to scroll to a certain point in the page and only then assert things about the page.

Both of these functions,

Ember.$('body').scrollTop(1000);

window.scroll(0,1000);

when followed by an

andThen(()=>{
    console.log('body', Ember.$('body').scrollTop());
}) 

print out that the body scrollTop position is at 108. I need it to be at 1000.

The only way I can get to the moment where body scrollTop is at 1000 is when I use this callback so far:

Ember.$('body').animate({scrollTop: 1000}, () => {
  console.log('body', Ember.$('body').scrollTop());
  staticWiz.assertHasGoToTopButton(true);
});

The problem here is that none of the test stuff exists by the point where this callback happens. I can't assert anything.

If I try to use assert.async() and done() with this callback, it makes it fire prematurely when the body scrollTop() is at 108:

const done = assert.async();
Ember.$('body').animate({scrollTop: 1000}, () => {
    console.log('body', Ember.$('body').scrollTop());
    staticWiz.assertHasGoToTopButton(true);
    done();
});

If I set a recurring timeout as a way to check the scroll position, it just stays at the same position of 108 forever.

const done = assert.async();
window.scroll(0, 1000);
const checkScroll = () => {
  console.log('body', Ember.$('body').scrollTop());
  if (Ember.$('body').scrollTop() === 1000) {
    staticWiz.assertHasGoToTopButton(true);
    done();
    return;
  }
  setTimeout(checkScroll, 1000);
};
checkScroll();

So. Any ideas? Has anyone gotten this working before for them, in an instance where you can't just have any degree of scrolling but need a specific number with an Emberjs acceptance test?




Ember js - model not refreshed with new query params

// controllers/list.js
import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['page', 'sortBy', {
    refreshModel: true
  }],
  page: 1,
  sortBy: 'createdAt'
});

and

// templates/components/list-table.hbs
Sort by name

Why list model is not fully refreshed, when I click "Sort by name" link? What I'm doing wrong? Thanks for any help.




Ember-CLI- TypeError: Cannot convert a Symbol value to a string

I am trying to compile my Cordova code for iOS but somehow when I try to run "ember serve" in /app/www/ folder then I get this error:

(node:21854) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
(node:21854) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
version: 0.1.7
Looks like you have a different program called watchman, falling back to NodeWatcher
Cannot convert a Symbol value to a string
TypeError: Cannot convert a Symbol value to a string
at RegExp.test (native)
at Symbol.hasOwnProperty (/Users/apple/Desktop/bob/we/source-code/code/app/www/node_modules/ember-cli/node_modules/es6-module-transpiler/dist/es6-module-transpiler.js:163:43)
at /Users/apple/Desktop/bob/we/source-code/code/app/www/node_modules/6to5-core/node_modules/core-js/library.js:136:17
at setToStringTag (/Users/apple/Desktop/bob/we/source-code/code/app/www/node_modules/6to5-core/node_modules/core-js/library.js:88:13)
at /Users/apple/Desktop/bob/we/source-code/code/app/www/node_modules/6to5-core/node_modules/core-js/library.js:610:3
at /Users/apple/Desktop/bob/we/source-code/code/app/www/node_modules/6to5-core/node_modules/core-js/library.js:614:2
at Object. (/Users/apple/Desktop/bob/we/source-code/code/app/www/node_modules/6to5-core/node_modules/core-js/library.js:2101:2)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)

Please suggest me how to fix this.




Ember build for production took more than expected time

I'm developing an Ember application, in that application

Building application for production environment gives following warning during build process.

>>ember build --environment production
WARNING: Node v7.2.1 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js.
/ Building[WARN] `assets/vendor.js` took: 27201ms (more than 20,000ms)
cleaning up...
Built project successfully. Stored in "dist/".
File sizes:
 - dist/assets/vendor-55a426e75e5239020a12bb7bfc6ffc2a.js: 759.74 KB (195.13 KB gzipped)
 - dist/assets/vendor-d41d8cd98f00b204e9800998ecf8427e.css: 0 B

i want to suppress these waning messages, for this i tried --silent with command.

ember build --environment production --silent

Still im getting following warning:

[WARN] `assets/vendor.js` took: 27201ms (more than 20,000ms)

cam some one tell me how to suppress this warning or fix this?




How can I get the Id from the URL in an Ember Route?

I have a two panel display where I show a list of items on the left, then detail about a selected item on the right (using nested route).

My route looks like this:

Router.map(function() {
 this.route('authenticated', {path: '/'}, function() {
  this.route('bakery', function() {
   this.route('cakes', function() {
    this.route('detail', { path: '/:id' });
    });
  });
});
});

My URL looks like
http://localhost:3333/bakery/cakes/e34b3ce3

When an item is selected, it is set to "active" (temporary property on the model - default is false) and highlighted via an action on the bakery/cakes route. The detail is then shown on the right.

If I refresh the page, the item is no longer highlighted - but the detail is still shown.

Ideally I'd like to use the afterModel() hook in the bakery/cakes route to set that item back to active again, but I've been unable to get the Id to be able to do this.

I've tried the following:

  • Accepted answer from here

  • This question doesn't help me as the model will have reloaded and my "active" property will be false so I can't just select where active = true.

I'm using ember 2.5.0. Thanks.




Emberjs belongsTo is null

I'm trying to build a "love" feature and I need to detect whether the user has already loved a book to show a different icon:

screenshot

From the above screenshot, if a user has already "loved" a book, then the heart will be filled in as shown.

I have a computed property called hasLoved which looks like this:

hasLoved: Ember.computed('model', function() {
  let book = this.get('model');
  let userID = this.get('apiManager.currentUser.id');
  // let loves = book.get('loves').filterBy('sender.id', userID);
  let loves = book.get('loves');
  console.log('loves count = ', loves.get('length'));

  for(var i = 0; i < loves.get('length'); i++) {
    let love = loves.objectAt(i);
    console.log('love book = ', love.get('book.id'));
    console.log('love sender = ', love.get('sender.id'));
  }

  return loves.get('length') > 0;
}),

The issue is my book's list of loves doesn't have the sender set for some odd reason.

If you look at the console log in the above screenshot, it says "love sender = undefined".

Even though my Ember is pulling in the data:

{
    "data": {
        "id": "31",
        "type": "loves",
        "attributes": {
            "book": {
                "id": 16,
                "title": "Three Little Pigs",
                "adult_content": false,
                "author_id": 2,
                "created_at": "2016-12-10T09:47:25.103Z",
                "updated_at": "2016-12-10T09:47:25.103Z",
                "published": true,
                "cover": {
                    "url": "http://localhost:3000/uploads/book/cover/16/three_little_pigs.jpg"
                },
                "blurb": "The Three Little Pigs is a fable/fairy tale featuring anthropomorphic pigs who build three houses of different materials. A big bad wolf blows down the first two pigs' houses, made of straw and sticks respectively, but is unable to destroy the third pig's house, made of bricks."
            },
            "sender": {
                "id": 21,
                "first_name": null,
                "last_name": null,
                "username": null,
                "email": "chewedon+tycus@gmail.com",
                "role_id": 3,
                "created_at": "2016-12-15T09:33:07.123Z",
                "updated_at": "2016-12-15T09:33:37.757Z",
                "photo": {
                    "url": null
                }
            }
        },
        "relationships": {
            "book": {
                "data": {
                    "id": "16",
                    "type": "books"
                }
            },
            "sender": {
                "data": {
                    "id": "21",
                    "type": "users"
                }
            }
        }
    }
}

My models are defined as follows:

Love

import DS from 'ember-data';

export default DS.Model.extend({
  book: DS.belongsTo('book', { inverse: 'loves' }),
  sender: DS.belongsTo('user', { inverse: 'loves' })
});

Book

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  blurb: DS.attr(),
  adultContent: DS.attr('boolean', { defaultValue: false }),
  published: DS.attr('boolean', { defaultValue: false }),
  cover: DS.attr(),
  attachment: DS.attr('file'),
  chapters: DS.hasMany('chapter', { inverse: 'book' }),
  author: DS.belongsTo('user', { inverse: 'books' }),
  loves: DS.hasMany('love', { inverse: 'book' }),
  favourites: DS.hasMany('favourite'),
  comments: DS.hasMany('comment')
});

User

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

export default DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr(),
  username: DS.attr(),
  email: DS.attr(),
  photo: DS.attr(),
  books: DS.hasMany('book', { inverse: 'author' }),
  loves: DS.hasMany('love', { inverse: 'sender' }),

  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  })
});




Ember push JSON response into store with irregular pluralization

So I have a Love model in my EmberJS application (Facebook likes if you want to think of it that way). A reader can love a book at the following URL:

POST http://localhost:3000/loves

My method to make this is a ajax call from the Ember side is:

Ember.$.ajax({
  type: "POST",
  url: this.get('apiManager').requestURL('loves'),
  dataType: 'json',
  headers: {"Authorization": "Bearer " + jwt},
  data: params
}).done((response) => {
  console.log('response = ', response);
  let love = this.get('store').push(response);
  let book = this.get('model');
  console.log('love = ', love.get('id'));
  console.log('love book id = ', love.get("book"));
});

I tried setting up a love-inflector inside app/models/love-inflector.js like this:

import Inflector from 'ember-inflector';

const inflector = Inflector.inflector;


inflector.irregular('love', 'loves');

inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');

// Meet Ember Inspector's expectation of an export
export default {};

When I try to love a book, I get the following error:

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

screenshot of error

Anybody know what steps I am missing?

Update

According to the Ember guides:

http://ift.tt/2ia3bm4

The store's push() method is a low level API which accepts a JSON API document with a few important differences from the JSON API document that the JSONAPISerializer accepts. The type name in the JSON API document must match the type name of the model exactly (In the example above the type is album because the model is defined in app/models/album.js). Attributes and relationship names must match the casing of the properties defined on the Model class.

My JSON response from the Rails server looks like this:

{
    "data": {
        "id": "5",
        "type": "loves",
        "attributes": {
            "book": {
                "id": 16,
                "title": "Three Little Pigs",
                "adult_content": false,
                "author_id": 2,
                "created_at": "2016-12-10T09:47:25.103Z",
                "updated_at": "2016-12-10T09:47:25.103Z",
                "published": true,
                "cover": {
                    "url": "http://localhost:3000/uploads/book/cover/16/three_little_pigs.jpg"
                },
                "blurb": "The Three Little Pigs is a fable/fairy tale featuring anthropomorphic pigs who build three houses of different materials. A big bad wolf blows down the first two pigs' houses, made of straw and sticks respectively, but is unable to destroy the third pig's house, made of bricks."
            },
            ...
        },
        "relationships": {
            "book": {
                "data": {
                    "id": "16",
                    "type": "books"
                }
            },
            "sender": {
                "data": {
                    "id": "21",
                    "type": "users"
                }
            }
        }
    }
}

I was hoping my inflector would pick up the "loves" in the above JSON and convert it to "love", taking care of that problem for me...but it doesn't appear that's the case...




lundi 19 décembre 2016

Ember 2.10.x help for use Page Layout (Splitter) and ideas to begin and structure an EmberJs Application

enter image description here

1. Question:

I want to use an Splitter with the plugin The Ultimate Page Layout Manager http://ift.tt/1DlUYn4.

The only way i know is to create a component and use didInsertElement to initialize the plugin. Is there another way to initialize the plugin without creating a component?

2. Question

Short Explanation: I'm unsure how to structure my application with components and templates, has someone any tips based on the wireframe example?

Note: Im a new Ember Fan and want to create my first application, therefore please dont be sally if i dont know all the Ember Way Stuff.

Long Explanation: My Problem: Im not really sure how to structure my EmberJs Application with the new DND recommendations. Components are the new main structure concept and im not really sure i understand the concept exactly.

For illustration purpose, i made a simple Wireframe.

Now My Questions based on the structure of the Wireframe:

Should i use components for each ui-part, or templates?

Image the following scenario:

There is and selectbox in the navbar, this selecbox holds objects with an width proberty, who can be changed by the user. If the width is changed the right Panel with the Splitter will update to the new size (for example 500px).

I understand components should be safe ans self isolated, to be able to use the components in different scenarios or projects.

But i have the logical requirement to send a specific action from the component to the application action handler to change the

<< Wireframe >>




Accessing metadata attr on template

I have a mocked api endpoint with ember-cli-mirage and with some metadata. I did override the model serializer to add that metadata like this:

import { JSONAPISerializer } from 'ember-cli-mirage';

export default JSONAPISerializer.extend({
    serialize(object, request) {
        let json = JSONAPISerializer.prototype.serialize.apply(this, arguments);

        json.meta = {
            compass_size: 1,
            arrow_size: 2,
            total: 3
        }

        return json;
    }
});

The api call returns that metadata correctly:

Object
    data: Array[10]
    meta: Object
     arrow_size: 2
     compass_size: 1
     total: 3
     ...

Given I have this route handler:

import Ember from 'ember';

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

When I try to print that data on my template



then nothing is rendered. Am I missing something?




Rails API + Ember Authentication Implementation

As title suggest i would like to implement user authentication to my ember+rails app.FYI, there are separate apps.I am fairly new to both frameworks and this topic took me over 3 weeks already to solve.I have tried over 5/6 tutorials.None of them was up to date so none of them worked.I am surprised how something so common can ended up so hard to solve for me.

How do you guys implement it? What steps do you guys take to accomplish this task?

I have learned the basics of Ember Simple Auth.I actually can authenticate an ember app with a mock server (mirage).But when it comes to rails, everything has failed so far :(.

Please help me on this matter




how to deal with custom events in ember.js component?

I'm new to Ember.js and I've got some problems to understand its philosophy. I know actions up, data down but in real life, lets say I have Fotorama initialized in my-gallery component (I don't know if that is ok, but I did it in didInsertElement method). This library has its own events. They could look like this in plain JS:

$('.fotorama').on('fotorama:ready', function (e, fotorama) {});

or:

$('.fotorama').on('fotorama:show', function () {});

but I feel in Ember, those should be somehow mapped into actions in component. My question is: how? I need to fire some actions (to be catched by another components or maybe a router) inside those actions. So I think it should be like this: this.sendAction('actionName', actionParams);




Why is Object.get('key') undefined in Ember?

javascript

So even if I define the keys and values using .set() I'm still getting object.get('key') is undefined. There is one example in the image above.




Dynamic panel loading driven in serverside

I have a usecase(common) and I'm searching for right technology... Pls suggest..

Usecase: create dynamic panels based on user selection.

We have a drop down box where user can chose a value based on which I'll be loading some html components(can be text box,drodown,etc) in a div..some of these html components are common and some are specific to the value chosen in drop down..

Right now we have jsps , n lot of if-elses to determine whether to load the component or not...This has grown to an extent where maintenance takes a huge effort..

What I'm looking for:

Whether we can drive these panels in Java(serverside) with any technology or any other idea is appreciated..




How can I get the parameter in Ember.js?

I'm new in Ember. And I want to know how to get the parameter in .js.

It's my source

:: normal page calling component

<h4>WaterMark Page</h4>

::component.js

// I want to get all of parameter here.

import Ember from 'ember';
import layout from '../templates/components/comp-watermark';
export default Ember.Component.extend({
  layout
});

::component.hbs

<div>
 WaterMark Component.
</div>

<div>Parameter01 : </div>
<div>Parameter02 : </div>

//also I want to seperate using type which is parameter from normal-page

<button type="button" class="btn btn-default">Default</button>
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-link">Link</button>




dimanche 18 décembre 2016

ember-i18n translate text with double curly braces

How to translate this Ember template text:

<p>The 's tasks in ""</p>




Fetch new data from API in jQuery plugin's callback

I am new to ember, so please treat me like a fool. What I'm trying to do first is to understand the concept.

In my application I heavily rely on few jQuery plugins they fetch new portion of data in their callbacks, that's how these plugins are designed, but I am not sure how can I trigger them to fetch a new portion of data from API passing to API updated query parameters after plugin has been rendered.

I have wrapped the plugin in a component, in component's template I send data to it as (I use emblem.js syntax here)

= plotly-chart chartData=model

In model I have

//app/models/data-points.js

import DS from 'ember-data';

export default DS.Model.extend({
    // time: DS.attr(),
    ch1:  DS.attr(),
    ch2:  DS.attr(),
    ch3:  DS.attr(),
    temperature:  DS.attr(),
});

And then in component itself I fetch data

//app/components/plotly-chart.js

dataPoints: Ember.computed.map('chartData', function(item){
    return item.getProperties('ch1', 'ch2', 'ch3', 'temperature');
}),

and make some manipulations with data, which isn't so important for the question itself.

Ah, and I have a route graph/ which later calls that component

//app/routes/graph.js

import Ember from 'ember';

export default Ember.Route.extend({
    queryParams: {
        start_timestamp: {
            refreshModel: true
        },
        end_timestamp: {
            refreshModel: true
        }
    },
    model(params) {
        return this.get('store').query('data-point', params);
    }
});

So as you see I have tried to fetch new properties via query params, finally it works great if I just update the url in browser, but now can I trigger new call to API and fetch new data and get this new data in a component itself?

Also I'm struggling to understand what role controllers play in all of these. It is mentioned that controllers will be deprecated soon, but still used here http://ift.tt/2hORzpq My code seems to work without controllers, so this is really confusing.

Also I suspect maybe I should use services for what I'm trying to achieve, but not sure how.

Ember experts, could you please point me into a right direction? The most important thing is how to fetch new portion of data from API with updated query parameters (query parameters to API itself, not nessesarely the ember application, but I suspect in ember-data it is the same thing? or not %) %) %)).




Ember 2.11.X How to get the Input value of and component through the action handler

Problem: I want to transfer the changed value from the input-field component to the action, but i recieve only the initially value.

The controller holds the variable width with an initially of 100, but should update after the value changed in the input field.

        <form  class="form-inline waves-effect waves-light" style="width:50px">
                 
        </form>

sdf




Iterating over object with hasMany relationship

I'm stuck trying to iterate over model object that has hasMany relationship.

Object is Question and it has many question-rows.

Inside route "grouping" I want to display all question and select one (using power select) and display table of question rows for selected question.

import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
const { RSVP } = Ember;

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    selectedQuestion: null,
    model() {
        const survey = this.modelFor('survey');

        return RSVP.hash({
            questions: this.get('store').query('question', { surveyId: survey.get('id') }),
        });
    },
    actions: {
        toggleIsInversed(id) {
        }
    }
});

This is component grouping-table and it is loaded with selectedQuestion.

 
<table class="ui celled table unstackable">
    
    <thead>
        <tr>
            <th>Text</th>
            <th>Group</th>
            <th>Inverse</th>
        </tr>
    </thead>
    <tbody>
        
        <tr>
            <td></td>
            <td>Group A</td>
            <td>
                
            </td>
        </tr>
        
    </tbody>
</table>
 




Cannot deploy ember app in firebase

I am unable to deploy my ember application in firebase I can only see the welcome page of firebase hosting.

You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!

I have installed the emberfire add on as well as the firebase tool.

My config file looks this way :

    module.exports = function(environment) {
      var ENV = {
        modulePrefix: 'sample',
        environment: environment,
        rootURL: '/',
        locationType: 'auto',

        firebase : {
        apiKey: 'xxxxxx',
        authDomain: 'xxxxx',
        databaseURL: 'xxxx',
        storageBucket: 'xxxxx',
        messagingSenderId: 'xxxxx'
    }, 
        EmberENV: {
          FEATURES: {
            // Here you can enable experimental features on an ember canary build
            // e.g. 'with-controller': true
          }
        },

        APP: {
          // Here you can pass flags/options to your application instance
          // when it is created
        }
      };

      if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        ENV.APP.LOG_ACTIVE_GENERATION = true;
        ENV.APP.LOG_TRANSITIONS = true;
        ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        ENV.APP.

LOG_VIEW_LOOKUPS = true;
  }

Firebase.json looks this way :

{
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

I have built the app and deployed using following commands

ember build --prod

firebase login

firebase init

firebase deploy

Thanks in advance :-)




Torri FireBase Authentication EmberFire

Extending the ToriiFirebaseAdapter by the code below, results in an error: ember.debug.js:16905 Assertion Failed: You cannot pass undefined as id to the store's find method".

The find method is called from within the "_findOrCreateUser" (code pasted below), any help appreciated.

import Ember from 'ember';
import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';

export default ToriiFirebaseAdapter.extend({
  firebaseApp: Ember.inject.service(),
  store: Ember.inject.service(),
 
  /**
   * Executed after Firebase authentication.
   *
   * Find or create the user based on the Firebase `authData`
   *
   * @param  {Object} authData
   * @return {Promise<Object>} Updated session info
   */
  open(authData) {
    return this._findOrCreateUser(authData)
      .then((user) => {
        return { currentUser: user };
      });
  },

  /**
   * Fetch an existing Firebase auth session and place into `session.currentUser`
   *
   * @return {Promise<Object>} Updated session info
   */
  fetch() {
        let ref=this.get('firebaseApp');
    console.log(ref);
    let authData = ref.auth();

    if (!authData) {
      return Ember.RSVP.Promise.reject(new Error('No Firebase session found'));
    }

    return this._findOrCreateUser(authData)
      .then((user) => {
        return { currentUser: user };
      });
  },

  /**
   * Teardown a session. Remove the `session.currentUser`.
   *
   * @return {Promise<Object>} Updated session info
   */
  close() {
    this.get('firebaseApp').unauth();
    return Ember.RSVP.Promise.resolve({ currentUser: null });
  },

  /**
   * Find the user with the given `authData`, create if not found
   *
   * @param  {Object} authData
   * @return {Promise<Object>} The user
   */
  _findOrCreateUser(authData) {
    let store = this.get('store');

    return store.find('user', authData.uid)
      .catch(() => {
        let newUser = store.createRecord('user', this.extractUserProperties(authData));

        return newUser.save();
      });
  },

  /**
   * Extract the user properties from `authData` that you care about.
   *
   * @param  {Object} authData
   * @return {Object} An updated property hash
   */
  extractUserProperties(authData) {
    var name = 'Unknown';
    var provider = authData.provider;
    var userData = authData[provider];

    if (userData.displayName) {
      name = userData.displayName;
    } else if (userData.username) {
      name = userData.username;
    }

    return {
      id: authData.uid,
      name: name,
      email: userData.email || null
    };
  }
});



Can't get ember engines running

I've created a standalone routable engine with ember-engines 0.4.0, ember-cli 2.10.0.

I get this error if I call the engines index route (/things/):

Assertion Failed: Asset manifest does not list any available bundles.

Consuming App router.js:

this.mount('things', { as: 'things' });

Engine App routes.js:

this.route('index', { path: '/' });

The engine is 'installed' via a symlink in the node_modules/ dir of the consuming ember-cli app. (See here why).

Just for fun I've tried to change the routes to test if that works ...

Consuming App router.js:

this.mount('things', { as: 'things' });

Engine App routes.js:

this.route('index', { path: 'new' });

I've called /things/new and got an UnrecognizedURLError.

Also if I place a console.log('...'); in the engines index.js, I can't see any output. Seems like it isn't loaded at all.

The setup was inspired by the official README and the official example repos.

Any idea how to fix this Ember Engines setup?




samedi 17 décembre 2016

Is it possible to configure database or model root paths?

TL;DR: When using Firebase with Ember through EmberFire, Is there a way to define the root location where changes should be saved in the firebase database, either for the entire ember instance, or on a per-model basis?

Example: given a secret model, which by default would store a new secret in /secrets/<secret GUID>/, could we configure EmberFire to instead use a sub-path as the root, so a new secret would be created at: /<some_path>/secrets/<secret GUID>/?


Suppose we have a firebase database configured to support multiple versions of an app during development:

{
  "versions" : {
    "0_0_1" : {
      "isActive" : true
    },
    "0_0_2" : {
      "isActive" : false
    }
  }
}

And this secret.js model:

import DS from 'ember-data';

export default DS.Model.extend({
  content     : DS.attr('string', { defaultValue() { return "UNDEFINED"; } }),
});

By default, when saving a new secret object, a 'secrets' section is created at the root of the database:

{
  "versions" : {
    "0_0_1" : { ... },
    "0_0_2" : { ... }
  },
  "secrets" : {
    "<GUID>" : { "content" : ... }
  }

}

It could be that in 0.0.2 the 'secret' model is no longer used, and so it would be nice if instead we could configure EmberFire to just store the secret objects as a child of /versions/0_0_1/:

{
  "versions" : {
    "0_0_1" : {
      "isActive" : true,
      "secrets" : {
        "<GUID>" : { "content" : ... }
      }
    },
    "0_0_2" : {
      "isActive" : false
    }
  },
}

Ideally I want to configure my ember app to just treat the location /versions/0_0_1/ as if it was the database root.

So as far as the app is concerned, the database consists only of:

{
  "isActive" : true,
  "secrets" : {
    "<GUID>" : { "content" : ... }
  }
}


I understand that in production you really should only have one firebase database per version of the app if the object schema drastically changes, but unfortunately google only provides so many free databases to use, and so it would be nice when testing to be able to have multiple apps accessing the same database, just using different sub-paths.

When I tried changing firebase.databaseURL in config/environment.js from <MyApp>.firebaseio.com/ to <MyApp>http://.firebaseio.com/versions/0_0_1/ I get an error saying

FIREBASE FATAL ERROR: Database URL must point to the root of a Firebase Database (not including a child path)

so I'm assuming this may not be not supported, at least via the databaseURL configuration option. Is there perhaps another option that could be used instead?

Alternatively, is there a way on a per-Model basis to configure a root path instead of a global one?




Emberfire/Torii Adapter

I extended the ToriiFireBaseAdapter as follows with a fetch method:

 
  fetch() {
        let ref=this.get('firebaseApp');
    console.log(ref);
    let authData = ref.getAuth();

    if (!authData) {
      return Ember.RSVP.Promise.reject(new Error('No Firebase session found'));
    }

    return this._findOrCreateUser(authData)
      .then((user) => {
        return { currentUser: user };
      });
  },

There is an error on the line "let authData = ref.getAuth();" "ref.getAuth is not a function". How do I fix this and what is the best debug tool for this, so that i can inspect the object and ascertain what methods are available on the object?




Ember 2.10 : How do include templates from pods with partial

My Pod structure is: pods/navbar/template.hbs and try to include this template in the application.hbs.

I am not be able to include the template as partial, couse i recieve an error in the console.

*Uncaught Error: Compile Error: * is not a partial*

What i have to do, to include partical templates in other templates? What's the right spelling?

pods/navbar




In Ember what is the best way to stop propagation with select tag

In Ember I want to have a parent div that when clicked will call an action, except if a select tag is clicked within that div. I eventually came up with a solution but it's not very good and was wondering if someone could explain why bubbles=false does not work in this case, and how I can get access to the event on the selectValue action (details below).

Originally I had:

<div class="parent-class" >
    <select onchange=>
        <option class="default-option" disabled selected value>-</option>
        
            <option value= selected=></option>
        
    </select>
</div>

But I didn't want the action 'shouldNotBeCalledOnSelect' to be called when the select tag is clicked. I tried bubbles=false on the selectValue action, but this didn't work. I couldn't think of a way to pass the event with the selectValue action as it is, if I could then I could call

event.stopPropagation();

With an action you can get the event by using

onclick=

and then the event can be retrieved in the Javascript as the last parameter. The solution I have achieved, which is a bit rubbish, is to have both onchange and onclick events on the select tag and use onclick exclusively for stopping propagation.

<div class="parent-class" >
    <select onchange= onclick=>
        <option class="default-option" disabled selected value>-</option>
        
            <option value= selected=></option>
        
    </select>
</div>

In the javascript I then have:

selectValue(value) {
    this.set('score.value', value);
    this.get('score').save();
},

stopPropagation(event) {
    event.stopPropagation();
},

shouldNotBeCalledOnSelect() {
    console.log("CALLED");
}




vendredi 16 décembre 2016

Which of the Javascript frameworks should I go forward with? Why?

I am heading towards advanced web development and mobile apps development (specifically android), I want to know which javascript frameworks should I study, like I have heard React Native can be used for both android and ios app development.

There are so many of Javascript frameworks,

1.Angular

2.Node

3.Vue

4.React

5.Jquery

6.Socket

7.Polymer

8.Meteor

9.Ember

10.Mercury

and there are so many out there! Which one should I go with ? Which is better and for what?




How can I have a collection that contains only persisted Ember Data records, excluding records that live on the client-side and are not persisted?

Assuming I have 3 users in the backend:

let users = this.get('store').findAll('user'); 
console.log(users.get('length'));// => 3, e.g. [{id: 1}, {id: 2}, {id: 3}] 
this.get('store').createRecord('user');
console.log(users.get('length')); // => 4, e.g. [{id: 1}, {id: 2}, {id: 3}, **{id: null}**]   

How can I retrieve a list of only persisted records, i.e., only records that have an ID assigned to them?

I realize that I can manually filter records that has no ID whenever I need to consume persisted users, but that looks messy and counterintuitive.
Most importantly with a manual approach I can't keep one reference to the collection, like what I had in the users variable there, meaning the collection can't be computed, doesn't updates with new records, etc.
I skimmed through Ember's docs but I found nothing of use, have I missed something there?
How can I only get a collection of persisted records from Ember's store?




In Ember, how do I transmute sticky query parameters a user enters?

Fairly new to Ember so I apologize if I'm using the wrong terminology here. I have a form with sticky parameters that's binding a user modifying that form to the URL also changing, but I'd like to run an additional transformation (for example, hashing that value), but I'm not sure how to hook into this behavior.

My initial reaction was to hook into didTransition as it looks like this fires every time the form is modified, but it doesn't look like didTransition has access to the query parameters. I'd appreciate any help here.




jeudi 15 décembre 2016

Ember Engines inside Rails Engines via ember-cli-rails

We have a high modular rails5 app, which is splitted in rails engines over serveral repositories and integrated as ruby gems.

Now we want to introduce EmberJS by using ember-cli-rails. The main rails application contains the main ember application in the frontend directory while each of the rails engines contain an ember engine (via ember-engine) in a frontend directory.

How to mount the ember engines of the modules into the main ember engine?




Emberjs not converting JSON to model array

From my Emberjs I am making a custom request to an explore route on my Rails server:

GET http://localhost:3000/explore

I see my JSON response in my Google Chrome network inspector, however, my page isn't rendering anything.

To make the custom request, I have a book adapter:

Book Adapter

import ApplicationAdapter from './application';
import Ember from 'ember';

export default ApplicationAdapter.extend({
  apiManager: Ember.inject.service(),

  findPublishedBooks: function(store, type) {
    let jwt = this.get('apiManager').get('jwt');

    return Ember.RSVP.resolve(
      Ember.$.ajax({
        type: "GET",
        url: this.get('apiManager').requestURL('explore'),
        dataType: 'json',
        headers: {"Authorization": "Bearer " + jwt}
      })
    );
  }
});

Explore Route

model() {
  const adapter = this.get('store').adapterFor('book');
  return adapter.findPublishedBooks();
}

On my Rails side, I have this for my Explore action:

Rails Explore Action

def explore
  books = Book.where(published: true)

  if books.count > 0
    render json: books
  else
    return nil
  end
end

I know I must be doing something wrong, probably on my Ember side.




ember/npm addon with dependencies/ devDependencies

I have created an ember addon which relies on gulp derived packages to build, so in the addon it has the following in package.json.

When the addon is included in the main application, the build fails due to the various gulp modules being missing. The addon is in the devDependencies section of the main application.

The addon also builds into the main application when it is in through npm link. My question is how should the addon dependencies be handled so the main application builds without a local copy of the module?

Addon JSON file

{
  "name": "My Addon",
  "version": "0.0.0",
  "description": "The default blueprint for ember-cli addons.",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember try:each",
    "postinstall": "gulp build && bower install"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/myaddon.git"
  },
  "engines": {
    "node": ">= 0.12.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "bootstrap": "^4.0.0-alpha.5",
    "broccoli-asset-rev": "^2.4.5",
    "broccoli-funnel": "^1.0.9",
    "ember-ajax": "^2.4.1",
    // more ember modules
    "find-root": "^0.1.1",
    "font-awesome": "^4.7.0",
    "glob": "^4.5.3",
    "gulp": "^3.9.1",
    "gulp-clean-css": "^2.2.1",
    "gulp-concat": "^2.6.0",
    "gulp-connect": "^2.2.0",
    "gulp-filter": "^3.0.1",
    "gulp-git": "^1.4.0",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^2.3.2",
    "gulp-sourcemaps": "^1.5.2",
    "gulp-task-loader": "^1.2.1",
    "gulp-template": "^3.0.0",
    "gulp-uglify": "^1.2.0",
    "gulp-zip": "^3.0.2",
    "lazypipe": "^1.0.1",
    "loader.js": "^4.0.10",
    "run-sequence": "^1.1.2"
  },
  "keywords": [
    "ember-addon"
  ],
  "dependencies": {
    "ember-cli-babel": "^5.1.7"
  },
  "ember-addon": {
    "configPath": "tests/dummy/config"
  }
}




Render only outlet template if outlet exists

I have route 'A' and subroute 'B'. I don't want to render the template of Route 'A' if the subroute 'B' is accessed. But if am I not at subroute level, I want to render the template of route 'A'.

Is there a way to achieve this? I tried following for template 'A':


    <h1>Subroute</h1>
    

    <h1>Route</h1>


Pity enough this does not work (outlet is a 'magic' word, it is not a normal variable). I could do it by using css's absolute positioning, but I would like to use a more Ember way if that's possible!




mercredi 14 décembre 2016

Ember 2.10, updating component on array pushObject

I have two components that should both reflect the same data (testing d3 in ember)

One of the components adds a node to my state and also lists those nodes. The state is an array and I believe I am correctly calling pushObject in order to notify everything that there are updates.

The other is going to be a d3 thing so nothing is being rendered by the hbs file and I need to be notified when the array is modified so I can call the appropriate d3 functions and rerender my force graph.

I setup a minimal twiddle here: http://ift.tt/2hvAXpu

Basically, when you press add node: it adds a node to the list so I know some event is being fired however, my draw function in the "twiglet-graph" component is not being called.

To see this in action, goto the fiddle and press "Add". When you add another node, it will correctly list two nodes on the top part but it never changes the length in the bottom component to 2. I setup a click event that will alert you of the length of that component's this.nodes and clicking after adding shows a length of 2. How do I hook into the update so I can redraw my force graph?

Thanks.




Ember IntelliSense Support for Visual Studio 2013?

As titled, is there Ember intelliSense support can be install for Visual Studio 2013?




npm start doesn't work after i do npm unlink

npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/myName/.nvm/versions/node/v5.12.0/bin/node" "/Users/myName/.nvm/versions/node/v5.12.0/bin/npm" "start"
npm ERR! node v5.12.0
npm ERR! npm  v3.8.6
npm ERR! code ELIFECYCLE
npm ERR! appName@1.5.1 start: `ember server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the appName start script 'ember server'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the appName package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ember server
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs appName
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls appName
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/myName/Documents/Dev/ember-project-name/npm-debug

I linked gooey, one of my projects, to another project: ember, now i wanted to unlink them so i did npm unlink then npm start didn't work no matter what i did. things I've tried: npm install several times, bower install several times, rm -rf node_modules rm -rf bower_components npm install several times npm start kept giving errors, like can't find some file in gooey or tell author that ember server failed