I am trying to use a fairly simple Handlebars helper within an #each loop going over the items in a controller's model (it's a collection of models supplied by EmberData using the fixtureAdapter). Here's the basic layout of the template:
{{#each}}
....
{{#each clusters}}
<span>{{prettifyTimestampTime cluster_timestamp}}</span>
{{/each}}
{{/each}}
Here is my helper (in coffeescript):
Ember.Handlebars.registerBoundHelper 'prettifyTimestampTime', (timestamp, options) ->
d = new Date timestamp
hours = String(d.getHours() % 12)
hours = "0#{hours}" if hours.length is 1
"#{hours}:#{d.getMinutes()}:#{d.getMinutes()}"
I originally set this helper on Handlebars itself with Handelbars.registerHelper, but I kept getting the string "cluster_timestamp" passed in (no matter what I put after prettifyTimestampTime in the template, it would get resolved to a String).
I then followed suit and attempted to give stukennedy's answer a try by wrapping the property in quotes and doing a lookup on options.data.keywords, but the key wasn't in that dictionary.
When I to tried to use Ember.Handlebars.registerBoundHelper instead, per Bradley Preist's suggestion here, the timestamp argument is simply undefined. I do notice that, when I try to access any properties on options.contexts[0], the values they point to are undefined, but the keys are there.
I feel completely lost at this point. Any direction is welcome. Is this really a known bug in Ember, as stukennedy has pointed out in the previous SO questions? Having just started with Ember and Handlebars, I would rather have this just be some dumb error on my end, considering how difficult it was for me to also to set up fixtures with Ember data in the first place. :-P
EDIT: After seeing this question, I realize why registerHelper did not work (because it does not try to associate what is passed in with the property of the current object in context). However, I'm still just as lost since the lookup of the property isn't working. Perhaps this is an Ember Data issue with promises? The only thing that makes me confused about that being the case is that I am using fixtures (no request made), and I am able to get at the property cluster_timestamp normally with a normal expression like {{cluster_timestamp}}.
don't use registerHelper, http://emberjs.com/guides/templates/writing-helpers/
Ember.Handlebars.helper 'prettifyTimestampTime', (timestamp, options) ->
d = new Date timestamp
hours = String(d.getHours() % 12)
hours = "0#{hours}" if hours.length is 1
"#{hours}:#{d.getMinutes()}:#{d.getMinutes()}"
Related
I set up a simple Ember Twiddle to show you my error that is occurring when trying to update a model.
It's considerable that I'm using ember-cli-mirage for mocking the data.
According to the docs, I created a shorthand route that should handle the PUT request.
It does, but with the error: Your handler for the url /api/shops/1 threw an error: Cannot convert undefined or null to object
When using the JSONAPISerializer, everything is working with shorthands (mirage/config.js) and I'm able to update models, but in my case I have to use the RESTSerializer with serialized IDs in the responses.
The request payload when I'm sending the model's attrs are without Id at the end of the property name, f.e.:
// attrs object in PUT request
{
name: "Shop 1",
city: "1" // belongsTo relationship,
}
Now Mirage is trying to find those properties on the respective database model that has to be updated, but cannot find it, because in the database it's cityId and not just city...
I also found this issue report and it’s working, but I was hoping I could avoid something like this. As far as I can remember, in previous versions of ember-cli-mirage (v0.1.x) it was also not needed to override the normalize method in the serializer to be able to make use of the RestSerializer with serializedIds…
My question is:
Is there a way to stick to shorthand route handlers only, or do I really have to write a helper or other custom solution only because I have to use the RestSerializer?
That would be really sad, but at least I would know then.
Thanks for your support!
Short answer: it looks like you need the custom serializer for now until the bug fix for it is merged.
Long answer: that issue looks to be an issue that occurred in the 0.2 -> 0.3 upgrade for Mirage, likely because of underlying DB changes made in Mirage. It'll probably get fixed, but for now you'll need to work around it.
On my route im requesting via ember-data some records. Lets say the model-type is 'item'.
model: function(){
return this.get('store').find('item');
}
now ive got a component named 'my-foo' which should use the records to do something with the data. Therefore Im calling the component like that:
{{my-foo myItems=model}}
in my routes template. In the components js part, Im trying to get the myItems-field and iterate over them.
this.get('myItems').forEach(...);
Unfortunalety its not clear for me if the model i want to overgive to the component is an collection from records or just a single record (since on some routes the model is the result of store.find('item') on other store.find('item', 23424).
How can I check what kind of data arrives in the component.
(Also Im wondering what kind of object is it since im using ember-data. Is it a DS.recordarray or a promise or something else at this time?)
I can see two solutions to the problem:
Making component aware of the form that model receives
Checking and/or adjusting data type in component (in my opinion better default scenario)
As for making component aware - you could go with 2 approaches. Either differentiate in a way how your component take arguments, so there could be:
{{my-foo myItems=model}} - when you expect to receive multiple items
{{my-foo item=model}} - when you expect to receive single one
And then work accordingly further on, or - the second approach - is to actually split component (while extracting shared part to a different structure) so you would have my-foo for single items and my-foo-array for multiple.
Advantage of this approach is that you don't deal with what-if-multiple logic, that might grow to something unmanagable later on, yet usage of it is dependant on project requirements.
As for checking and/or adjusting - you already have data in, so could make assumption that your data is dirty and sanitize it using computed property. Below example, where single item is wrapped into an array.
export default Ember.Component.extend({
sanitizedItems: Ember.computed('items', function() {
var items = this.get('items');
if(!Array.isArray(items)) {
return [items];
} else {
return items;
}
})
});
Since you're using Ember.Data, depending on your setup, you might get a promise instead of object/array. In this case, you might want to resolve promise using this.get('items').then(function(items) { ... }) before doing sanitization, yet the idea behind is exactly the same.
You can check full example: Gist, Twiddle
Lets say I want that my page's title will change depending on a really simple field what is the Ember way of doing it?
I didn't really understand the bindings in Ember, do I have to create an object even if all I need is just 1 field?
Does Ember support two way bindings? if it does so how can I constrain the bindings to one-way only?
I think i'm a bit confused with Ember-data & regular Ember, when I use Ember-data do I need to care about bindings at all?
Thanks in advance :)
This is a little vague (or I just don't fully understand what you're asking), so I'll shotgun approach and we can narrow down as you ask more questions.
Preface: Ember Data is a client side record management library, Ember works completely fine without it.
Title
A page's title is a little tricky since it's kind of out of the scope of the viewable dom, but the best way to handle it would be with an observer. In the example below, as the title property changes inside of my application controller I'm setting the document.title.
App.ApplicationController = Em.Controller.extend({
title:undefined,
watchTitle: function(){
document.title = this.get('title');
}.observes('title')
})
Example: http://emberjs.jsbin.com/haducafu/1
Computed Properties
Ember does support one way bindings (though rarely do you need to care about bindings). More often you want to care about dependent properties. eg if property a has changed, property b should be updated etc. In the case below, b is a computed property that depends on a, if a changed, b is dirty, and ember should re-computed it.
App.ApplicationController = Em.Controller.extend({
a:'foo',
b: function(){
return 'Hello: ' + this.get('a');
}.property('a')
})
Example: http://jsbin.com/haducafu/2/edit
Simple Binding
Additionally Ember can do just simple bindings (you can actually skip defining name, since ember would define it the first time it uses it).
App.ApplicationController = Em.Controller.extend({
name:undefined
});
<h2>Hello {{name}}</h2>
Name: {{input value=name}}
Example: http://jsbin.com/haducafu/3/edit
One Way/Read Only:
One way will take the value from its host property, unless you set it, if you set it it stops following the dependent property and becomes its own (not modifying the dependent property).
Read only will take values form the host property, and if you try and set it it will blow chunks.
App.ApplicationController = Em.Controller.extend({
name:'billy',
oneWay: Em.computed.oneWay('name'),
readOnly: Em.computed.readOnly('name')
});
Try changing name first, they will all update, then change oneWay and it will diverge and never return, then change readOnly and it will throw errors.
Example: http://jsbin.com/haducafu/4/edit
I'm JS beginner and recently using ember.js for ui development I came across a problem that I can't solve.
I'm trying to reduce amount of posts to fit them on one page. Simply calling slice method on return value of this.get('store').find() doesn't work. I also tried to trim content of return value of all function, but still without success. Any ideas?
You can use the following:
App.YourController = Ember.ArrayController.extend({
arrangedContent: function() {
return this.get('content').slice(0 , 10);
}.property('content')
});
Where YourController is the controller that belongs to your route. So the content will be the resolved promise from this.store.find('modelName'). The arrangedContent property is the place where you modify the content when you want to perform filtering, ordering etc. Without changing the content directly and preserving all the data.
Give a look in that sample http://jsfiddle.net/marciojunior/pwQ5b/
If you really are calling slice on the return value of this.get('store').find you will run into trouble. The find function returns a promise and you need the result the promise resolves to.
You can solve this in one of two ways:
If you are using the standard Ember pattern for loading in your model, you should have a model function defined in your route. This will actually wait until the result is resolved and in your controller you can call slice on this.get('content')
If you are loading your data within the controller you will need to so something like below:
c = this
this.store.find('myModel').then(function(result) {
c.set('paginatedContent', result.slice(0, 10));
});
Here we are waiting for the promise returned by find to resolve to a result before setting the paginated content based on that result.
I been trying to compare some values in handlebars if statement {{#if value == 'otherValue'}}, obviously unsuccessfully because handlebars do not like this and expecting a string, boolean, or function name. Well that would be ok, but then I tried to pass parameter in the function like you can do with {{action}} helper, and well that didn't workout either, got this in console
Error: assertion failed: You must pass exactly one argument to the if helper
So then I decided to do this in a View, even so ember js guides points that accessing template values in-scope is unusual and they provide only poor paragraph with no examples.
http://emberjs.com/guides/understanding-ember/the-view-layer/#toc_accessing-template-variables-from-views
So when I tried to do this, I got a problem of accessing those variables, I tried this way this.get('controller.templateVariables') and via full path to View, but value was either undefined or .get() wasn't exists as a method.
So at this moment I decided to save variable in the DOM data property, but turns out this {{#view App.TabsView data-title="{{tab}}"}} is going to literately give me a string {{tab}} when I try to access it from View with this.get('data-title').
The only way left to me was to insert additional element inside view and store variable there, and afterwards access it with jQuery class selector. but element is not yet exist in the DOM at the time of isVisible function gets executed, so I have no access to values at that time. That explains why this.get('element') was returning null.
Similar examples on ember js mostly ends up with something like if (someLogic) {}, but how I can do any logic when there is no variables available to me.
Question
To simplify my question - is there a way how I can do such a thing in ember js? Simple as
// have objects stored in controller
var obj = [{title:'Tab1'}, {title:'Tab2'}, {title:'Tab3'}];
// loop via them in the DOM
obj.forEach(function(tab) {
// do this kind of comparison
if( tab.title == currentTab() ) {
// do something here
}
});
If that is not possible, then what would be the other way to achieve similar functionality?
You can write a handlerbar helper to do this
{{activeTab tab}}
Handlebars.registerHelper('activeTab', function(tab) {
})
See a question about the same issue
Active Tab
Or look at existing helpers to write your own
Bind Helper
Template Helper
I think the best way for me to demonstrate this is with a heavily commented JSFiddle that I've put together for you: http://jsfiddle.net/PbLnm/
Please ask any questions below if you're not sure about anything.
The main part which determines when to add the active class is in the computed property:
// Determine if the object we have for this view is the same as the activeTab's object. If it is the same, then this view is the current active tab.
active: function() {
return Boolean(this.get('parentView.activeTab') == this.get('tab'));
}.property('parentView.activeTab')