Menu
  • HOME
  • TAGS

Access model in controller-action?

Tag: ember.js,handlebars.js,ember-cli,controller-actions

I'm editing an object with a form and want to save the changed object from within the controller-action which is bound to the submit-button. I don't want to bind the values directly to the template.

Here's the admin/edit.hbs

<form>
    <label>Title
      <input name="title" type="text" {{ bind-attr value=title }} />
    </label>
    <label>Permalink
      <input name="permalink" type="text" {{ bind-attr value=permalink }} />
    </label>
    <label>Post
      {{textarea value=body cols="80" rows="12"}}
    </label>
  <button {{ action 'submitAction' }}>Submit</button>
</form>

This is the controller admin/edit.hbs import Ember from 'ember';

export default Ember.ObjectController.extend({    
  actions: {
      submitAction: function() {
        var newTitle = this.get('title');
        // how to access the model here?
      }
    }
});

Best How To :

Assuming that the model you want is currently the model of your ObjectController, you can do one of two things:

  1. Get the model directly:

    submitAction: function() {
        var model = this.get('model');
    }
    
  2. Pass it to the handler in the template:

    // admin/edit.hbs
    <button {{action 'submitAction' model}}>Submit</button>
    
    // admin/edit.js
    submitAction: function(model) {
    
    }
    

Rerendering Handlebars template upon data change

jquery,handlebars.js

Handlebars does not handle data binding to update on value changes. You may use a framework like ember which comes with two-way data binding. A vanilla way to perform re-rendering upon data change is using Object.observe: Object.observe(someJsonObject, function() { template(someJsonObject); }); ...

How to get data out of ember objects

javascript,ember.js,kendo-grid

You could use getProperties method. http://emberjs.com/api/classes/Ember.Object.html#method_getProperties To get the values of multiple properties at once, call getProperties with a list of strings or an array: record.getProperties('firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } You could define computed property dataArray: dataArray: function() { return this.get('data').map( function(item) {...

Assign two actions to one element in Ember.js

ember.js

That link no longer really applies - Views are being removed from Ember. The way to do it is with a component for your span element: Handlebars {{my-span on-click=(action 'handleComponentSpanClick') on-context-menu=(action 'handleComponentSpanContextMenu')}} JavaScript App.MySpanComponent = Ember.Component.extend({ tagName: 'span', click: function(e) { this.attrs['on-click'](e); }, contextMenu: function(e) { this.attrs['on-context-menu'](e); } }); Ember...

Handlebars does not output anything

javascript,gruntjs,handlebars.js,yeoman,bower

I found my solution with the last line of this JSFiddle. I gave the tag where the template was an ID, and used: $('#tagIDName').append(template(driver)); instead of just template(driver);...

Can we access Ember.TEMPLATES in controller?

javascript,templates,ember.js

Maybe this will work for you this.container.has('template:someName') As a someName you can put i.e. inbox.index or inbox/index...

When creating a new data object in Ember that relies on another object how do you pass it along?

ember.js,ember-cli

There are many points to fix: 1) {{controllers.customer}} is Controller Object, {{controllers.customer.name}} it's name property. I think you want {{controllers.customer.model.name}}. 2) "..newOrder.customer = customer.." should be newOrder.set('customer', this.get('controllers.customer.model')); 3) your customer.order.create route model hook shoudn't be empty, since you are using dynamic segment customer_id: //route model: function(params) { return this.find('customer',...

return first element from array as computed property from Ember controller subclass

javascript,arrays,model-view-controller,ember.js

This would work. Long way (just to improve your computed property code): // controller work.js import Ember from "ember"; export default Ember.Controller.extend({ firstElement: function () { return this.get('model').get('firstObject'); // or this.get('model.firstObject'); }.property('model.[]') }); 1) you set works as model in route, so you could get it as model in controller...

Connect to a RESTful service which ends all URLs with an “/”

ember.js,ember-data

Overriding the buildURL method from DS.RESTAdapter and appending a slash should do the trick: App.ApplicationAdapter= DS.RESTAdapter.extend({ buildURL: function() { var url = this._super.apply(this, arguments); return url + '/'; } }); ...

How do you force Ember to rerender a component?

javascript,jquery,ember.js

Without looking at code, I'm going to guess based on your statement of the model changing. Component Currently uiSetup: function(){ // do magic here... }.on('didInsertElement') Component with observes Assuming the model in the component is named model, this would fire every time the model changed as well as when the...

Sorting data by timestamp on ember

ember.js,ember-data,ember-cli

You have to use deprecated Ember.ArrayController instead of Ember.Controller if you want your approach to work or you can choose other approach. The best approach is to use Ember.computed macro: export default Ember.Controller.extend({ needs: ['application'], commentsSorting: ['timestamp:desc'], comments: Ember.computed.sort('model.comment', 'commentsSorting') }); Then, instead of model, iterate over comments in your...

Fetching API data from Ember Controller

ember.js,ember-data,ember-cli

First of all, when you execute store.find('modelName'), Ember REST API Adapter expects an array of models in response. Then, promise of store.find resolves with array of objects, and you have to get first object to see if success === true. this.store.find('validemail', {'email':'abc.gmail.com'}).then(function(validEmails){ console.log(validEmails.get('firstObject.success')); // true || false }); API method:...

In Ember 1.13 and later what key should I use with each when iterating over an array of strings?

ember.js,ember-cli

UPDATE (Jun,18) In Ember 1.13.2 default key="@identity" is used, to prevent users from having to specify a key= to each {{each}} invocation. @guid and @item are deprecated in favor of the new default. https://github.com/emberjs/ember.js/releases/tag/v1.13.2 https://github.com/emberjs/ember.js/pull/11461 ================= Answer for Ember 1.13, 1.13.1 ========= You could use key="@index" or key="@item". There are...

How to get the clicked element on Ember Component

ember.js,ember-cli

Ember.EventDispatcher delegates some events to the corresponding Ember.View. Since Ember.Component is a subclass of Ember.View, you can capture click events just exposing a click function: export default Ember.Component.extend({ click: function (event) { console.log(event.target); // displays the clicked element console.log("Hello from component"); } }); Keep in mind that using directly these...

Handlebars: return hash from helper

javascript,backbone.js,coffeescript,handlebars.js,handlebars

Handlebars will see this: {{show.key1}} as an attempt to access the key1 property of the show variable, it won't know that show in this case is supposed to refer to your show helper. This is just part of Handlebars syntax and I don't think there's anything you can do about...

How to run action in Ember Controller afterRender

ember.js,ember-data,ember-cli

You could use init: App.Controller = Ember.Controller.extend({ init: function () { this._super(); Ember.run.schedule("afterRender",this,function() { this.send("foo"); }); }, actions: { foo: function() { console.log("foo"); } } }); ...

What are Element Style Components and What are Fragment Style Components?

javascript,ember.js

First of all Element and Fragment RFC was superseded by Component Unification (angle brackets), so if you want to track this subject check the latter. In very simple words, Ember.Fragment is a tagless component. Presently if you don't want a component to have a surrounding div you have to do...

What's the best way to map objects into ember model from REST Web API?

json,rest,ember.js,asp.net-web-api,ember-data

I think this should fix your problem: export default DS.RESTSerializer.extend({ primaryKey: 'inventory_id' }); With this parameter Ember Data will map inventory_id to it's id parameter....

Polymer 1.0 in Ember-cli, wrong appearance

javascript,ember.js,polymer,frontend,ember-cli

i have been trying to use polymer 1.0 with ember for the last month, turns out some polymer elements that use as insertion points will not work with ember. I have spoken with a polymer core member and he said they are curerntly working in some interop to get things...

Custom API calls with Ember Data

ember.js,ember-data,ember-cli

You'll want to override the urlForFindQuery method in your adapter. Looking at the default source here, you can probably come up with something pretty simple: export default DS.RESTAdapter.extend({ urlForFindQuery(query, modelName) { const url = this._buildURL(modelName); return `${url}?first_name||last_name=*${query.search_term}*`; } }); Obviously that's not a fully working example, but hopefully you get...

Ember: How to get computed properties from a nested model?

ember.js,ember-cli,rsvp-promise

just return an array, and populate the array after the fact. allAlphas: function() { var self = this, returnValue = []; this.get('model.method').then(function(method) { //get the practices return method.get('practices'); }).then(function(practices) { //get the alphasField in EVERY practice //the alphasField is the (hasmany 'alpha')member in practice var alphas= practices.getEach('alphas'); Ember.RSVP.all(alphas).then(function(resolvedAlphas) { resolvedAlphas.forEach(function(afs){...

Ember.js - Rendering additional data for a model

javascript,ember.js,ember-data

The easiest way is to retrieve the data in the Route's afterModel handler: var ShowRoute = Ember.Route.extend({ model: function(params) { // Load the model and return it. // This will only fire if the model isn't passed. }, afterModel: function(model, transition) { // Load the rest of the data based...

Reference RSVP hash from inside the same hash

ember.js,hash

Ember.RSVP.hash() is good to avoid encoding the actual promise order. When order is important you could use promise chaining. model: function(params) { var self = this; return this.store.find('flyer', params.flyer_id).then(function(flyer) { return Ember.RSVP.hash({ flyer: flyer, images: self.store.find('image', flyer.get('imagesID')) }); }); }, In your special case you use route dynamic param params.flyer_id,...

ember model rendering strange behaviuor

ember.js

You could try to resolve model.player.ledger in afterModel hook: afterModel: function(model) { var controller = this.controllerFor('purchase'); model.get('player').then(function(player) { controller.set('player', player); return player.get('ledger'); }).then(function(ledger){ controller.set('playerLedger', ledger); }, function(error) { console.log("promise is not resolved", error); }); } In template {{player.name}} | {{playerLedger.title}} I think you could see why model.player.ledger is not resolved...

Recreate Similar Travis CI Console Log Interface

css,ember.js,travis-ci

"travis-web" uses Ember, but the functionality for the "log-container" is custom. It contains the text of the log file ("Download Log"). Please download a raw version of a log and take a look. You will see, that the log file has several "annotations". It's a syntax to indicate the areas,...

How to properly unbind jQuery window event handler in Ember component

jquery,ember.js

Your option is to either namespace the event like this: jQuery(window).on('resize.handleResize', Ember.run.bind(this, this.handleResize)); and then use: $(window).off('resize.handleResize'); to unbind the event (without providing the function). Here is more about event namespacing: https://css-tricks.com/namespaced-events-jquery/ The other way would be to save the reference to the function like this: ... this.set('boundResizeHandler', Ember.run.bind(this, this.handleResize))...

Bind more controller properties to one attribute using HTMLBars

ember.js,htmlbars

Using a computed property is probably best here. Another potential solution is ember-truth-helpers which would allow you to write code such as: <input disabled={{or model.isInvalid model.isSaving}}> I use ember-truth-helpers a lot, but that just looks weird and I wouldn't recommend it....

sortable list in emberjs

ember.js,ember-data,handlebars.js

Unfortunately sorting the items with jQuery UI doesn't actually change the order of the items. You might want to look into the addon ember-sortable - it should provide you all the functionality you need....

Ember.js binding to and saving belongsTo property

ember.js,ember-data

In Ember when you save a model other models don't get saved. You need to save each model by itself. I suggest you create a separate view for each model and save it individually because you might run into consistency issues. Anyway, here's how you'd save both models. var model...

Mapping Ember methods to API

ember.js,ember-data,rails-api

This is pretty basic and well-covered in the docs. createRecord followed by a save generates a POST on /apinamespace/things. save on an existing record generates a PUT on /apinamespace/things/thingID. destroyRecord, or deleteRecord followed by a save, generates a DELETE on /apinamespace/things/thingID. The Ember Data store and model methods themselves, by...

ember build Parse error on line 1: {{#each messages as |message|}}

ember.js,ember-cli

I think you might be using old version of HTMLBars and/or Ember CLI. You should upgrade to Ember CLI 0.2.7 from ^0.1.11(that's weird you're using ^ here, because upgrading from each version of Ember CLI requires some steps to take) and ember-cli-htmlbars to 0.7.6. Here's the valid package.json file for...

How to make Ember Cli Mirage to work with Ember Simple auth

javascript,ember.js,oauth-2.0,ember-simple-auth,ember-cli-mirage

For custom work like this, pass a function in as the second parameter to your route definition: this.post('/token', function(db, request) { // generate a token return { token: token }; }); I'd have to know more about your backend to offer more specific guidance, but this is the general idea....

How to get Ember compoment's “ID” attribute?

jquery-ui,ember.js

Ember Component has a elementId property which returns the id of the element in the DOM. so you can get the component's id using `this.get('elementId'). More info here: http://emberjs.com/api/classes/Ember.Component.html#property_elementId

Referencing handlebars variable in a loop

javascript,handlebars.js

My answer is that I was using two different versions of Handlebars. The project has v2.0.0 but npm installed 3.0.3 for the grunt task which compiles the templates.

Ember Simple Auth - injecting current user into every route

ember.js,dependency-injection,ember-simple-auth

This works for me on: ember-cli: 0.2.7 (ember: 1.12.0, ember-data: 1.0.0-beta.18) ember-cli-simple-auth: 0.8.0-beta.3 Note: ember-data: 1.13. Store is registered in an initializer, should work as is ember-data: 1.0.0-beta.19. Store is registered in an instance-initializer, some adjustments needed 1) Customize session //config/environment.js ENV['simple-auth'] = { session: 'session:custom', ... } //app/sessions/custom.js import...

ember-data stores a string instead of a number

ember.js,ember-data

Okay, I think I know what's going on. Setting input type to number won't help here. Value is still recognized as string. Usually when you submit form, backend anyway returns this value formatted as a number and problem's gone. You can see this even when you mock your data with...

How do I communicate the form parameters from the template to the route in ember.js?

forms,ember.js

1. About Controllers If you do not like to use controllers this would work for you (but I do not recommend you to follow this way): export default Ember.Route.extend({ actions: { add: function() { alert(this.controllerFor( this.get('routeName') ).get('name')); } } }); In fact, if you use name in template: {{input value=name}}...

js event in a handlebars template

javascript,jquery,handlebars.js

i mean: <script> alert('table before: ' + String($('#lodgerSearchResultTable'))); $( document ).ready(function() { alert('table after: ' + String($('#lodgerSearchResultTable'))); $('#lodgerSearchResultTable > tbody').dblclick(function () { alert($(this).text()); }); }); </script> other non-clear solution <script> $( document ).ready(function() { $('#lodgerSearchResult').dblclick(function (event) { console.log(event.target); var res_table = $('#lodgerSearchResultTable > tbody'); if( res_table ) {...

Can ember-cli watch and build automatically without running the server?

ember.js,ember-cli

If I understand correctly you are wanting the ember build command to watch for changes in the file tree and rebuild on a change? They implemented ember build --watch a while back which will trigger when a file changes. Tested just now and it worked on 0.2.7. Not sure what...

Refactoring Computed Properties on Ember.js 1.13

ember.js

filteredPosts: function(){...}.property('var1','var2','var3') should become: filteredPosts: Ember.computed('var1', 'var2', 'var3', function() { ... }); It's because prototype extensions are discouraged in recent versions of Ember and seems like you've encountered a problem related to prototype extensions. It'd be best if you create a demo of this issue, but Ember.computed should just work....

Emberjs advanced sort hasMany association as a computed property

sorting,ember.js,has-many,computed-properties

Ok first of all your JSBin had many issues so lets go throw them one by one 1- you did not include any Ember-Data build, so I included 1, this is needed for the fixtures and the models <script src="http://builds.emberjs.com/tags/v1.0.0-beta.15/ember-data.js"></script> 2- Your Scripts var App = window.App = Ember.Application.create({ });...

Express 4 register handlebars

javascript,node.js,handlebars.js

I tested some possible solutions, but this one was working as expected: var express = require('express'); var app = express(); var expressHbs = require('express3-handlebars'); app.engine('hbs', expressHbs({extname:'hbs', defaultLayout:'main.hbs'})); app.set('view engine', 'hbs'); app.get('/', function(req, res){ var data = {name: 'Gorilla'}; res.render('simple', data); }); app.listen(80); //--||--||--||--||--||--||--||--||--|| simple.hbs Showing <em>name</em> //--||--||--||--||--||--||--||--||--|| main.hbs <head>...

Does Handlebars require jQuery

javascript,jquery,handlebars.js

No, it doesn't require jQuery. Only reason why people prefer jQuery is because of ease of use with which jQuery perform various operations. It saves lots of time & additional effort. Using handlebars with plain javscript will require some extra effort. If you have enough time then you should try...

Ember Data “modelFor” error when serializing models

ember.js,ember-data,ember-cli

I have managed to fix the problem by re-installing ember-cli and ember-data. I assume something went awry during the upgrade process recently when I went from version 1.12.0 to 1.13.0 and ember-data 1.0.0-beta.17.0 to 1.0.0-beta.19.1.

Ember self-reference and polymorphism

ember.js,ember-data

As far as I understand there is no need in polymorphic here, because you wrote: "user model which also relates to itself". You should set reflexive relation contacts for user model. When you want to define a reflexive relation, you must either explicitly define the other side, and set the...

Emberjs get facebook friendlist

facebook-graph-api,ember.js,ember-data

You can use the Facebook JS API in the following manner: // app/initializers/facebook.js export function initialize(container, app) { app.deferReadiness(); window.__facebook.then(function() { app.advanceReadiness(); }); } export default { name: 'facebook', initialize: initialize }; In index.html: <script> (function(w) { var dfd = Ember.RSVP.defer(); w.__facebook = dfd.promise; w.fbAsyncInit = function() { FB.init({ appId...

Ember 1.13, view lookup

javascript,ember.js

I think you could operate your logic by model instances instead of views (I mean model concept here, it could be some array of objects or records array). It's clear you have model (as some array), since you mentioned multiple instances. You might do: {{!-- list of input fields --}}...

computed property that changes its value with action in Ember.js

javascript,ember.js,controller

You could define property selectedElement (that's clicked). When loadRight fired you could set selectedElement with selection. Then currentElement is simple computed property, depends on model.firstObject and selectedElement. export default Ember.Controller.extend({ firstElement: function () { return this.get('model.firstObject'); }.property('model.[]'), selectedElement: null, currentElement: function () { return (this.get('selectedElement') || this.get(`firstElement`)); }.property('firstElement', 'selectedElement'), actions:...

Model from Ember Data not rendering

javascript,ember.js,ember-data

Your problem is pluralization: you specify GamesModel instead of GameModel, you find games instead of game etc. I changed all these occurences to be aligned with what Ember expects(and you can read more about Ember standards in guides) and it works, CodePen: App.IndexRoute = Ember.Route.extend({ model: function(){ return this.store.find('game'); }...

Ember passing a model to transitionToRoute

ember.js,ember-cli,ember-router,ember-controllers

You are dealing with a classic problem occurring in many Ember applications which is how to handle "new"/"create" situations. You cannot define a route such as this.route('addcontact', { path: /addcontact/:thing_id } because the the new contact doesn't have an id, and won't until it is persisted to the server, at...