EmberJS: Call action from component in named block - ember.js

I am using named-blocks which I really like but I am unable to call an action from within them. This is an example of my code, the action works perfectly if not in the named-block
Controller
things = {
run: false,
walk: false,
jog: false,
}
#action
doSomething(thing) {
this.things[thing] = true;
}
Template
<MyComponent>
<:title>Some cool title...</:title>
<:button><MyButton {{on 'click' (fn this.doSomething 'run')}}/></:button>
</MyComponent>
MyComponent Template
<div>
{{yield to="title"}}
{{yield to="button"}}
</div>
MyButton Template
<button type="button>
Do a thing
</div>

given this component invocation
<MyButton {{on 'click' (fn this.doSomething 'run')}}/>
the MyButton component must have ...attributes in order to specify where to place attributes, modifiers, etc -- the "stuff on an element":
<button type="button ...attributes>
Do a thing
</button>

So to solve this I had to modify the templates like so:
<MyComponent>
<:title>Some cool title...</:title>
<:button><MyButton #clickAction={{fn this.doSomething 'run'}}/></:button>
</MyComponent>
<button type="button {{on 'click' #clickAction}}>
Do a thing
</div>

Related

Ember trigger action on wrapper component

I have a wrapper component that has an action that needs to be triggered from within, but I can't get rid of this:
{{#wrapper-component as |wrapper|}}
<button {{action 'wrapper.myAction'}}
{{/wrapper-component}}
the above is the template of "componentA"; when I click the button I get an error saying that componentA does not have an action handler for "wrapper.myAction"; I can't get why it looks for the action on componentA instead of wrapper-component first.
of course "myAction" is defined in "actions" on "wrapper-component";
the wrapper component has this template:
{{yield (hash myAction=(action 'myAction'))}}
Replace this:
<button {{action 'wrapper.myAction'}}
with this:
<button onclick={{action wrapper.myAction}}
please make sure you understand the difference between ember actions and closure actions.

ember action 'Nothing handled the action' within block component

If I have component in block form:
//some-component.hbs
{{#some-component}}
<button {{action "someAction"}}>test</button>
<!-- assume you have multiple buttons here with multiple actions -->
{{/some-component}}
//some-component.js
Ember.Component.extend({
actions: {
someAction() {
alert('NOT BEING CALLED');
}
}
});
using Ember > v2.0. The action is not being called.
If I call it:
{{some-component}}
and put:
<button {{action "someAction"}}>test</button>
inside the some-component.hbs template. then it works. but this way has some drawbacks which I want to avoid.
I've looked at the docs and everywhere it doesn't seem to have this sort of case.
the answer is:
{{yield this}}
in the template
and:
{{#some-component as |component|}}
<button {{action "someAction" target=component}}>TEST</button>
{{/some-component}}

getting back reference to a specific model using Ember's Array Controller

I'm new to Ember and am finding some of their concepts a bit opaque. I have a app that manages inventory for a company. There is a screen that lists the entirety of their inventory and allows them to edit each inventory item. The text fields are disabled by default and I want to have an 'edit item' button that will set disabled / true to disabled / false. I have created the following which renders out correctly:
Inv.InventoryitemsRoute = Ember.Route.extend({
model: function(params) {
return Ember.$.getJSON("/arc/v1/api/inventory_items/" + params.location_id);
}
<script type="text/x-handlebars" data-template-name="inventoryitems">
{{#each}}
<div class='row'>
<p>{{input type="text" value=header disabled="true"}}</p>
<p>{{input type="text" value=detail disabled="true"}}</p>
<button {{action "editInventoryItem" data-id=id}}>edit item</button>
<button {{action "saveInventoryItem" data-id=id}}>save item</button>
</div>
{{/each}}
</script>
So this renders in the UI fine but I am not sure how to access the specific model to change the text input from disabled/true to disabled/false. If I were just doing this as normal jQuery, I would add the id value of that specific model and place an id in the text input so that I could set the textfield. Based upon reading through docs, it seems like I would want a controller - would I want an ArrayController for this model instance or could Ember figure that out on its own?
I'm thinking I want to do something like the following but alerting the id give me undefined:
Inv.InventoryitemsController=Ember.ArrayController.extend({
isEditing: false,
actions: {
editInventoryItem: function(){
var model = this.get('model');
/*
^^^^
should this be a reference to that specific instance of a single model or the list of models provided by the InventoryitemsRoute
*/
alert('you want to edit this:' + model.id); // <-undefined
}
}
});
In the Ember docs, they use a playlist example (here: http://emberjs.com/guides/controllers/representing-multiple-models-with-arraycontroller/) like this:
App.SongsRoute = Ember.Route.extend({
setupController: function(controller, playlist) {
controller.set('model', playlist.get('songs'));
}
});
But this example is a bit confusing (for a couple of reasons) but in this particular case - how would I map their concept of playlist to me trying to edit a single inventory item?
<script type="text/x-handlebars" data-template-name="inventoryitems">
{{#each}}
<div class='row'>
<p>{{input type="text" value=header disabled="true"}}</p>
<p>{{input type="text" value=detail disabled="true"}}</p>
<button {{action "editInventoryItem" this}}>edit item</button>
<button {{action "saveInventoryItem" this}}>save item</button>
</div>
{{/each}}
</script>
and
actions: {
editInventoryItem: function(object){
alert('you want to edit this:' + object.id);
}
}
Is what you need. But let me explain in a bit more detail:
First of all, terminology: Your "model" is the entire object tied to your controller. When you call this.get('model') on an action within an array controller, you will receive the entire model, in this case an array of inventory items.
The {{#each}} handlebars tag iterates through a selected array (by default it uses your entire model as the selected array). While within the {{#each}} block helper, you can reference the specific object you are currently on by saying this. You could also name the iteration object instead of relying on a this declaration by typing {{#each thing in model}}, within which each object would be referenced as thing.
Lastly, your actions are capable of taking inputs. You can declare these inputs simply by giving the variable name after the action name. Above, I demonstrated this with {{action "saveInventoryItem" this}} which will pass this to the action saveInventoryItem. You also need to add an input parameter to that action in order for it to be accepted.
Ok, that's because as you said, you're just starting with Ember. I would probably do this:
<script type="text/x-handlebars" data-template-name="inventoryitems">
{{#each}}
<div class='row'>
<p>{{input type="text" value=header disabled=headerEnabled}}</p>
<p>{{input type="text" value=detail disabled=detailEnabled}}</p>
<button {{action "editInventoryItem"}}>edit item</button>
<button {{action "saveInventoryItem"}}>save item</button>
</div>
{{/each}}
</script>
with this, you need to define a headerEnabled property in the InventoryitemController(Note that it is singular, not the one that contains all the items), and the same for detailEnabled, and the actions, you can define them also either in the same controller or in the route:
App.InventoryitemController = Ember.ObjectController.extend({
headerEnabled: false,
detailEnabled: false,
actions: {
editInventoryItem: function() {
this.set('headerEnabled', true);
this.set('detailEnabled', true);
}
}
});
that's just an example how you can access the data, in case the same property will enable both text fields, then you only need one, instead of the two that I put . In case the 'each' loop doesn't pick up the right controller, just specify itemController.

Accessing properties of a child view created within {{#each}} iterator

Edit: Problem was with my own local settings and the way I was including the views in my application. Once I fixed those issues, the problem was resolves. The code here is actually correct. The answer Chrixian provided also work.
I am stuck on something that seems rather simple. I want to access some computed properties of my view constructed inside an each loop in handlebars.
<div class='build-buttons-wrapper'>
<button class="list-builds-button" {{action "toggleBuildsList" target="view"}} ></button>
<button class="build-button" {{action "buildApp" on="click" target="view"}} >Build</button>
</div>
<div class='builds-list'>
<h2 class="build-title">Latest builds</h2>
<ul class="builds-list">
{{#each content}}
{{#view Jimux.BuildView buildBinding="this"}}
<span class="build-date">{{createdAt}}</span>
<a {{bindAttr href="srcArchive"}} class="download-button source">Source</a>
{{! *here are different ways I have tried to access "finished" property* }}
{{log build.view.finished}}
{{log view.finished}}
{{log finished}}
{{log this.finished}}
{{log build.finished}}
{{#if build.finished}}
<div class="build-progressbar"></div>
{{else}}
<div class="build-progressbar"><div class="build-percent" style="width:{{unbound percent}}%"></div></div>
{{/if}}
{{/view}}
{{/each}}
</ul>
</div>
Here is the BuildsView which is using this template:
Jimux.BuildsView = Em.View.extend({
templateName: 'builds'
listVisible: false
classNames: ['builds-view']
buildApp: (view, event, ctx) ->
#get('controller').newBuild()
,
hideList: ->
#set 'listVisible', false
this.$(".builds-list").hide("slide", {direction: "up"}, 300)
,
showList: ->
#set 'listVisible', true
this.$(".builds-list").show("slide", {direction: "up"}, 300)
,
toggleBuildsList: (view, event, ctx) ->
if #get 'listVisible' then #hideList() else #showList()
,
didInsertElement: ->
#hideList() if not #get 'listVisible'
})
And here is the BuildView which is created inside the {{#each}} iterator in the template above.
Jimux.BuildView = Ember.View.extend(
tagName: 'div',
classNames: ['build-item'],
#testBinding: true,
sample: true,
finished: ( ->
return true
#return (#get 'percent') == 100
).property('percent')
)
Everything above works as expected. For example I can access percent property of each child view using {{percent}}. But if I define my own properties inside the Jimux.BuildView as show above, I cant seem to find a way to access them within the handlebars {{#each}} iterator. You can see the different ways I have tried inside the handlebars code with {{log}} statements, all those print undefined in the console. What am I missing here?
I'm assuming the percent property you are referring to is a property of each "content" object you are looping over-- if that's the case making finished look like this:
finished: (->
return #get('context.percent') is 100
).property('context.percent')
You should be able to simply use {{finished}} within the {{#view Jimux.BuildView}} .. {{/view}} block

Ember.js - Using a Handlebars helper to detect that a subview has rendered

There are numerous questions that ask in one way or another: "How do I do something after some part of a view is rendered?" (here, here, and here just to give a few). The answer is usually:
use didInsertElement to run code when a view is initially rendered.
use Ember.run.next(...) to run your code after the view changes are flushed, if you need to access the DOM elements that are created.
use an observer on isLoaded or a similar property to do something after the data you need is loaded.
What's irritating about this is, it leads to some very clumsy looking things like this:
didInsertElement: function(){
content.on('didLoad', function(){
Ember.run.next(function(){
// now finally do my stuff
});
});
}
And that doesn't really even necessarily work when you're using ember-data because isLoaded may already be true (if the record has already been loaded before and is not requested again from the server). So getting the sequencing right is hard.
On top of that, you're probably already watching isLoaded in your view template like so:
{{#if content.isLoaded}}
<input type="text" id="myTypeahead" data-provide="typeahead">
{{else}}
<div>Loading data...</div>
{{/if}}
and doing it again in your controller seems like duplication.
I came up with a slightly novel solution, but it either needs work or is actually a bad idea...either case could be true:
I wrote a small Handlebars helper called {{fire}} that will fire an event with a custom name when the containing handlebars template is executed (i.e. that should be every time the subview is re-rendered, right?).
Here is my very early attempt:
Ember.Handlebars.registerHelper('fire', function (evtName, options) {
if (typeof this[evtName] == 'function') {
var context = this;
Ember.run.next(function () {
context[evtName].apply(context, options);
});
}
});
which is used like so:
{{#if content.isLoaded}}
{{fire typeaheadHostDidRender}}
<input type="text" id="myTypeahead" data-provide="typeahead">
{{else}}
<div>Loading data...</div>
{{/if}}
This essentially works as is, but it has a couple of flaws I know of already:
It calls the method on the controller...it would probably be better to at least be able to send the "event" to the ancestor view object instead, perhaps even to make that the default behavior. I tried {{fire typeaheadHostDidRender target="view"}} and that didn't work. I can't see yet how to get the "current" view from what gets passed into the helper, but obviously the {{view}} helper can do it.
I'm guessing there is a more formal way to trigger a custom event than what I'm doing here, but I haven't learned that yet. jQuery's .trigger() doesn't seem to work on controller objects, though it may work on views. Is there an "Ember" way to do this?
There could be things I don't understand, like a case where this event would be triggered but the view wasn't in fact going to be added to the DOM...?
As you might be able to guess, I'm using Bootstrap's Typeahead control, and I need to wire it after the <input> is rendered, which actually only happens after several nested {{#if}} blocks evaluate to true in my template. I also use jqPlot, so I run into the need for this pattern a lot. This seems like a viable and useful tool, but it could be I'm missing something big picture that makes this approach dumb. Or maybe there's another way to do this that hasn't shown up in my searches?
Can someone either improve this approach for me or tell me why it's a bad idea?
UPDATE
I've figured a few of the bits out:
I can get the first "real" containing view with options.data.view.get('parentView')...obvious perhaps, but I didn't think it would be that simple.
You actually can do a jQuery-style obj.trigger(evtName) on any arbitrary object...but the object must extend the Ember.Evented mixin! So that I suppose is the correct way to do this kind of event sending in Ember. Just make sure the intended target extends Ember.Evented (views already do).
Here's the improved version so far:
Ember.Handlebars.registerHelper('fire', function (evtName, options) {
var view = options.data.view;
if (view.get('parentView')) view = view.get('parentView');
var context = this;
var target = null;
if (typeof view[evtName] == 'function') {
target = view;
} else if (typeof context[evtName] == 'function') {
target = context;
} else if (view.get('controller') && typeof view.get('controller')[evtName] == 'function') {
target = view.get('controller');
}
if (target) {
Ember.run.next(function () {
target.trigger(evtName);
});
}
});
Now just about all I'm missing is figuring out how to pass in the intended target (e.g. the controller or view--the above code tries to guess). Or, figuring out if there's some unexpected behavior that breaks the whole concept.
Any other input?
UPDATED
Updated for Ember 1.0 final, I'm currently using this code on Ember 1.3.1.
Okay, I think I got it all figured out. Here's the "complete" handlebars helper:
Ember.Handlebars.registerHelper('trigger', function (evtName, options) {
// See http://stackoverflow.com/questions/13760733/ember-js-using-a-handlebars-helper-to-detect-that-a-subview-has-rendered
// for known flaws with this approach
var options = arguments[arguments.length - 1],
hash = options.hash,
hbview = options.data.view,
concreteView, target, controller, link;
concreteView = hbview.get('concreteView');
if (hash.target) {
target = Ember.Handlebars.get(this, hash.target, options);
} else {
target = concreteView;
}
Ember.run.next(function () {
var newElements;
if(hbview.morph){
newElements = $('#' + hbview.morph.start).nextUntil('#' + hbview.morph.end)
} else {
newElements = $('#' + hbview.get('elementId')).children();
}
target.trigger(evtName, concreteView, newElements);
});
});
I changed the name from {{fire}} to {{trigger}} to more closely match Ember.Evented/jQuery convention. This updated code is based on the built-in Ember {{action}} helper, and should be able to accept any target="..." argument in your template, just as {{action}} does. Where it differs from {{action}} is (besides firing automatically when the template section is rendered):
Sends the event to the view by default. Sending to the route or controller by default wouldn't make as much sense, as this should probably primarily be used for view-centric actions (though I often use it to send events to a controller).
Uses Ember.Evented style events, so for sending an event to an arbitrary non-view object (including a controller) the object must extend Ember.Evented, and must have a listener registered. (To be clear, it does not call something in the actions: {…} hash!)
Note that if you send an event to an instance of Ember.View, all you have to do is implement a method by the same name (see docs, code). But if your target is not a view (e.g. a controller) you must register a listener on the object with obj.on('evtName', function(evt){...}) or the Function.prototype.on extension.
So here's a real-world example. I have a view with the following template, using Ember and Bootstrap:
<script data-template-name="reportPicker" type="text/x-handlebars">
<div id="reportPickerModal" class="modal show fade">
<div class="modal-header">
<button type="button" class="close" data-dissmis="modal" aria-hidden="true">×</button>
<h3>Add Metric</h3>
</div>
<div class="modal-body">
<div class="modal-body">
<form>
<label>Report Type</label>
{{view Ember.Select
viewName="selectReport"
contentBinding="reportTypes"
selectionBinding="reportType"
prompt="Select"
}}
{{#if reportType}}
<label>Subject Type</label>
{{#unless subjectType}}
{{view Ember.Select
viewName="selectSubjectType"
contentBinding="subjectTypes"
selectionBinding="subjectType"
prompt="Select"
}}
{{else}}
<button class="btn btn-small" {{action clearSubjectType target="controller"}}>{{subjectType}} <i class="icon-remove"></i></button>
<label>{{subjectType}}</label>
{{#if subjects.isUpdating}}
<div class="progress progress-striped active">
<div class="bar" style="width: 100%;">Loading subjects...</div>
</div>
{{else}}
{{#if subject}}
<button class="btn btn-small" {{action clearSubject target="controller"}}>{{subject.label}} <i class="icon-remove"></i></button>
{{else}}
{{trigger didRenderSubjectPicker}}
<input id="subjectPicker" type="text" data-provide="typeahead">
{{/if}}
{{/if}}
{{/unless}}
{{/if}}
</form>
</div>
</div>
<div class="modal-footer">
Cancel
Add
</div>
</div>
</script>
I needed to know when this element was available in the DOM, so I could attach a typeahead to it:
<input id="subjectPicker" type="text" data-provide="typeahead">
So, I put a {{trigger}} helper in the same block:
{{#if subject}}
<button class="btn btn-small" {{action clearSubject target="controller"}}>{{subject.label}} <i class="icon-remove"></i></button>
{{else}}
{{trigger didRenderSubjectPicker}}
<input id="subjectPicker" type="text" data-provide="typeahead">
{{/if}}
And then implemented didRenderSubjectPicker in my view class:
App.ReportPickerView = Ember.View.extend({
templateName: 'reportPicker',
didInsertElement: function () {
this.get('controller').viewDidLoad(this);
}
,
didRenderSubjectPicker: function () {
this.get('controller').wireTypeahead();
$('#subjectPicker').focus();
}
});
Done! Now the typeahead gets wired when (and only when) the sub-section of the template is finally rendered. Note the difference in utility, didInsertElement is used when the main (or perhaps "concrete" is the proper term) view is rendered, while didRenderSubjectPicker is run when the sub-section of the view is rendered.
If I wanted to send the event directly to the controller instead, I'd just change the template to read:
{{trigger didRenderSubjectPicker target=controller}}
and do this in my controller:
App.ReportPickerController = Ember.ArrayController.extend({
wireTypeahead: function(){
// I can access the rendered DOM elements here
}.on("didRenderSubjectPicker")
});
Done!
The one caveat is that this may happen again when the view sub-section is already on screen (for example if a parent view is re-rendered). But in my case, running the typeahead initialization again is fine anyway, and it would be pretty easy to detect and code around if need be. And this behavior may be desired in some cases.
I'm releasing this code as public domain, no warranty given or liability accepted whatsoever. If you want to use this, or the Ember folks want to include it in the baseline, go right ahead! (Personally I think that would be a great idea, but that's not surprising.)