ember-power-select Custom Search Action and 'selected' with external data - javascript

Overview
I'm using ember-power-select in a Ember.js 3.8 project - and it half works and half doesn't !
To make the question more readable I've put all the code at the bottom of the question.
Situation
The select is configured to fetch data from an API endpoint and provide the user with a set of possible options to select from.
The route (routes/guest/new-using-ember-power-select.js) involved does a createRecord of the model (models/guest.js) and then, ideally, changes made to both of the form elements (templates/guests/new-using-ember-power-select.js and templates/components/guest-form-ember-power-select.hbs) are reflected back into that record in the data store.
Issue
This works fine for the text input but I can't make it work for the ember-power-select.
In the current configuration (shown below) the user may :
search for options to select;
select an option and;
have that selection reflected back into the guest instance in the data store. However the choice made is not reflected in the user interface - there appears to have been no selection made.
I would really appreciate someone pointing out what I'm doing wrong here. I feel like it might be quite a small thing but it did occur to me that I have to manage the state of the select via properties in the component and only when the form is submitted update the underlying data-store .... I would prefer not to do that but I would be interested to know if that was thought to be the best idea.
Thanks
EDIT 1: I forgot to say that I have attempted to alter the onchange property of the ember-power-select so that instead of looking like this
onchange=(action "nationalityChangeAction")
... it looks like this ...
onchange=(action (mut item.nationality))
That has the effect that :
the value selected is visible in the form (as you would normally expect but unlike my current effort) but
the value placed into the underlying data store record is not a two character country code but instead an instance of the array returned the API call, an object with two properties {"name":"New Zealand","alpha2Code":"NZ"}.
Model
//app/models/guest.js
import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
name: [
validator('presence', true),
],
nationality: [
validator('presence', true),
],
});
export default DS.Model.extend( Validations, {
name: DS.attr('string'),
nationality: DS.attr('string')
});
Route
//app/routes/guest/new-using-ember-power-select.js
import Route from '#ember/routing/route';
export default Route.extend({
model() {
return this.store.createRecord('guest', {
name: "",
nationality: ""
});
},
actions: {
updateNationality(slctnValue) {
this.controller.model.set('nationality' , slctnValue);
},
}
});
Template
//app/templates/guests/new-using-ember-power-select.js
<h2>Guest: Add New</h2>
<div class="well well-sm">
Demonstration of 'ember-power-select'
</div>
{{guest-form-ember-power-select
item=model
changeNationalityHandler="updateNationality"
updateRecordHandler="updateRecord"
cancelHandler="cancelAndExit"
}}
{{outlet}}
Component Template
//app/templates/components/guest-form-ember-power-select.hbs
<div class="form-vertical">
{{!-- Guest Name --}}
<div class="form-group">
<label class="control-label">Name</label>
<div class="">
{{ input type="text"
value=item.name
class="form-control"
placeholder="The name of the Guest"
focus-out=(action (mut this.errMsgDspCntrl.nameError) true)
}}
</div>
{{#if this.errMsgDspCntrl.nameError}}
<div class="text-danger">
{{v-get item 'name' 'message'}}
</div>
{{/if}}
</div>
<div class="form-group">
<label class="control-label">Countries (using power-select)</label>
<div class="">
{{#power-select
searchPlaceholder="Text to provide user info about what they can search on"
search=(action "searchCountries")
selected=item.nationality
onchange=(action (mut item.nationality))
as |countries|
}}
{{countries.name}}
{{/power-select}}
</div>
{{#if this.errMsgDspCntrl.nationalityError}}
<div class="text-danger">
{{v-get item 'nationality' 'message'}}
</div>
{{/if}}
</div>
{{!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--}}
{{!-- Buttons --}}
<div class="form-group">
<div class="">
<button type="submit" class="btn btn-default" {{action "buttonSaveClicked" item}}>{{buttonLabel}}</button>
<button type="button" class="btn btn-default" {{action "buttonCancelClicked" item}} >Cancel</button>
</div>
</div>
</div>
{{yield}}
Component
//app/components/guest-form-ember-power-select.js
import Component from '#ember/component';
export default Component.extend({
actions:{
searchCountries(term) {
//Response to :
//
//https://restcountries.eu/rest/v2/name/z?fields=name;alpha2Code
//
//
//looks like this
// [
// ...
// {"name":"New Zealand","alpha2Code":"NZ"}
// ...
// ]
//
let url = `https://restcountries.eu/rest/v2/name/${term}?fields=name;alpha2Code`
let dbg = fetch(url)
.then(function(response) {
return response.json();
});
return dbg;
},
nationalityChangeAction(slctn){
this.sendAction('changeNationalityHandler', slctn.alpha2Code);
},
}
});

I'm going to answer showing some diffs with the changes required to make the select work in your repo: https://github.com/shearichard/emberjs-select-addon-comparison
The key thing to understand is that ember-power-select receives a block, in your case
as |country|}}
{{country.name}}
{{/power-select}}
That block will be called to render each of the options, but also the selected option. In this case, the options are country objects with this shape: {"name":"American Samoa","alpha2Code":"AS"}. That is why you call {{country.name}} to render it. However, with your approach, the selected value that you are passing in is not an object with a name property. In fact is not even an object, but the string "AS" in the case of American Samoa, so you can output the name property of a string.
In your situation, the information you store (the country code) is not enough to display a nice "American Samoa" in the trigger of the select, and since you don't know the countries before hand until you make a search you can't look the country with that country code.
If you don't have an edit form, my suggestion is to store the entire selected country in a property which is the one you pass to selected.
diff --git a/app/components/guest-form-ember-power-select.js b/app/components/guest-form-ember-power-select.js
index edf9390..2467d85 100644
--- a/app/components/guest-form-ember-power-select.js
+++ b/app/components/guest-form-ember-power-select.js
## -25,6 +25,8 ## export default Component.extend({
//messages
nameOfErrMsgDspCntrl : 'errMsgDspCntrl',
+ nationality: undefined,
+
actions:{
searchCountries(term) {
## -73,7 +75,7 ## export default Component.extend({
},
nationalityChangeAction(slctn){
- //this.set(this.myValue, slctn);
+ this.set('nationality', slctn);
this.sendAction('changeNationalityHandler', slctn.alpha2Code);
},
diff --git a/app/templates/components/guest-form-ember-power-select.hbs b/app/templates/components/guest-form-ember-power-select.hbs
index 56f007d..5c69834 100644
--- a/app/templates/components/guest-form-ember-power-select.hbs
+++ b/app/templates/components/guest-form-ember-power-select.hbs
## -24,7 +24,7 ##
{{#power-select
searchPlaceholder="Text to provide user info about what they can search on"
search=(action "searchCountries")
- selected=item.nationality
+ selected=nationality
onchange=(action "nationalityChangeAction")
as |countries|
}}
## -36,14 +36,14 ##
This works as long as you don't want to edit the nationality of a user you created before, perhaps even weeks ago. You won't have a reference to the country in that case, only the country code. In that situation I'd recommend making selected a computed property that returns a promise the resolves to the country object with the user's country code, if your API allows that. And seems that it does, so the BEST solution would be
diff --git a/app/components/guest-form-ember-power-select.js b/app/components/guest-form-ember-power-select.js
index edf9390..f889734 100644
--- a/app/components/guest-form-ember-power-select.js
+++ b/app/components/guest-form-ember-power-select.js
## -1,4 +1,5 ##
import Component from '#ember/component';
+import { computed } from '#ember/object';
export default Component.extend({
buttonLabel: 'Save',
## -25,6 +26,16 ## export default Component.extend({
//messages
nameOfErrMsgDspCntrl : 'errMsgDspCntrl',
+ nationality: computed('item.nationality', function() {
+ let countryCode = this.get('item.nationality');
+ if (countryCode) {
+ return fetch(`https://restcountries.eu/rest/v2/alpha/${countryCode}?fields=name;alpha2Code`)
+ .then(function (response) {
+ return response.json();
+ });
+ }
+ }),
+
This last one will fetch the information for the country you know the code of.

selected property must be an element included in options provided to Ember Power Select. In your scenario you are not using options property but setting the options through search action but that doesn't make a big difference.
Your search action return an array of objects (e.g. [{"name":"New Zealand","alpha2Code":"NZ"}]). nationalityChangeAction sets the selected value to the value of alpha2Code. Therefore selected is not included in options:
[{"name":"New Zealand","alpha2Code":"NZ"}].includes('NZ') // false
So the state your Power Selects ends in is similar to this one:
<PowerSelect
#options={{array
(hash foo="bar")
}}
#selected="bar"
/>
A simplified version of what you are doing look like this:
<PowerSelect
#options={{array
(hash foo="bar")
}}
#selected={{selected}}
#onchange={{action (mut selected) value="foo"}}
/>
Please have a look in Ember Power Select documentation regarding the difference between using options and search:
When that's the case you can provide a search action instead of options (it's the only situation where the options are not mandatory) that will be invoked with the search term whenever the user types on the search box.
[...]
There is only three things to know about this action:
- You should return a collection or a promise that resolves to a collection from this action.
- You can provide both options and a search action. Those options will be the initial set of options, but as soon as the user performs a search, the results of that search will be displayed instead.
Therefore it doesn't make a difference for your issue if you are using options or returning a collection from search action. It all comes down to having a selected value that is not part of the collection bound to options or returned by search action.
This is actually the reason why your UI is working as expected if using onchange=(action (mut item.nationality)). In that case item.nationality is that to the selected object in collection returned by search (e.g. {"name":"New Zealand","alpha2Code":"NZ"}) and not to the value of it's alpha2Code property.
I'm using angle bracket component invocation syntax in my answer. Hope that fine. It makes it easier to read it in my opinion.

Related

Django Rest Framework - get related FK object for use in template; POST not working now?

I've got a form up and working with a Vue frontend and DRF backend. It's a form for adding (creating) a new model - and has a dropdown of the related models that are FK to the model being created.
I need to access attributes of the selected FK item.
My serializers look like this:
class SubdomainSerializer(serializers.ModelSerializer):
class Meta:
model = Subdomain
fields = [
"id",
"domain",
"short_description",
"long_description",
"character_code",
]
# def get_absolute_url(self, obj):
# return obj.get_absolute_url()
class EvidenceSerializer(serializers.ModelSerializer):
created_by = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
updated_by = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
absolute_url = serializers.SerializerMethodField()
created_by_name = serializers.SerializerMethodField()
updated_by_name = serializers.SerializerMethodField()
class Meta:
model = Evidence
fields = "__all__"
The form is to create a new 'Evidence' item, and the 'Subdomain' is a dropdown on the form that contains all related subdomains.
The models look like this:
class Subdomain(CreateUpdateMixin):
domain = models.ForeignKey(Domain, on_delete=models.PROTECT)
short_description = models.CharField(max_length=100)
long_description = models.CharField(max_length=250)
character_code = models.CharField(max_length=5)
class Evidence(CreateUpdateMixin, CreateUpdateUserMixin, SoftDeletionModel):
subdomain = models.ForeignKey(Subdomain, on_delete=models.PROTECT)
evaluation = models.ForeignKey(
Evaluation, related_name="evidences", on_delete=models.PROTECT
)
published = models.BooleanField(default=False)
comments = models.CharField(max_length=500)
In my form, I just want to include the short_description of each subdomain when the user chooses it from the dropdown - I may also want to use the long_description as well.
Here is the bit in the form where I render the dropdown:
<div class="form-group col-sm-4">
<label class="" for="subdomain">Subdomain</label>
<select name="subdomain" id="subdomain" class="form-control" v-model="element.subdomain">
<option v-for="choice in subdomains" :value="choice.id" >{{ choice.character_code }}</option>
</select>
</div>
<div class="small" v-if="element.subdomain">
<!-- THIS IS WHERE I WOULD LIKE TO DISPLAY THE SHORT DESCRIPTION FOR THE CHOICE IN THE DROPDOWN -->
{{ choice.short_description }}
</div>
The Form Data looks like this when I POST:
evaluation: 2037
subdomain: 448
comments: Test comments to add to the subdomain
published: true
csrfmiddlewaretoken: 382796ryfuasiodfgyhakljyht37yaisdfaslk3r
Things I have tried - some of which worked for display purposes but seem to have broken the form/POST:
Adding depth=1 to the Meta of the EvidenceSerializer, which worked but made the form no longer submit appropriately. I think it's because it wanted the entire subdomain instead of just the ID? I couldn't get it working - the subdomain always threw an error.
Adding the following to my EvidenceSerializer, which again seemed to break the POST operation, it would cause the subdomain dropdown to throw an error.
subdomain = SubdomainSerializer(read_only=True)
Using both of those methods above the dropdown doesn't recognize the subdomain_id being selected and both end up throwing this error behind the scenes:
Cannot insert the value NULL into column 'subdomain_id', table 'local_app.dbo.myapp_evidence'; column does not allow nulls. INSERT fails.
Any advice on how to proceed would be fantastic.
TLDR; Need to be able to access attributes on a FK relationship for a dropdown using DRF, and be able to submit that item in a form.
Thanks to #bdbd for pointing me in the right direction.
For anyone curious, I resolved it using those links - turns out I needed to change my serializers a little bit:
class SubdomainSerializer(serializers.ModelSerializer):
class Meta:
model = Subdomain
fields = [
"id",
"domain",
"short_description",
"long_description",
"character_code",
]
class EvidenceSerializer(serializers.ModelSerializer):
created_by = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
updated_by = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
absolute_url = serializers.SerializerMethodField()
created_by_name = serializers.SerializerMethodField()
updated_by_name = serializers.SerializerMethodField()
# add the 'subdomain' as read only - but with all the attributes
subdomain = SubdomainSerializer(read_only=True)
# add the 'subdomain_id' as a PrimaryKeyRelatedField with the source being the subdomain
subdomain_id = serializers.PrimaryKeyRelatedField(
queryset=Subdomain.objects.all(), source="subdomain"
)
class Meta:
model = Evidence
fields = "__all__"
Then I updated the HTML a little bit:
<div class="form-group col-sm-4">
<label class="" for="subdomain_id">Subdomain</label>
<select name="subdomain_id" id="subdomain" class="form-control" v-model="element.subdomain">
<option v-for="choice in subdomains" :value="choice" >{{ choice.character_code }}</option>
</select>
</div>
<div class="small" v-if="element.subdomain_id">
{{ element.subdomain.short_description }}
</div>
Then in the ajax call I simply assign the subdomain_id to the subdomain.id
data: {
evaluation : evaluationId,
subdomain_id : vm.element.subdomain.id,
comments : vm.element.comments,
published: vm.element.published,
csrfmiddlewaretoken: vm.sharedStore.state.csrftoken,
},

VueJS/Laravel - Sharing props between Laravel and Vue

I have defined a component called EditorNavigation.vue like so:
<template>
<div>
<ul>
<li v-bind:class="{'is-active':(active === field.id)}" v-for="field in fields">
<a :href="'/streams/' + stream_token + '/fields/' + field.id">{{field.name}}</a>
</li>
</ul>
<div>
</template>
<script>
export default {
props: ["fields", "active", "stream_token"],
created() {
this.fields = JSON.parse(this.fields);
this.active = JSON.parse(this.active);
this.stream_token = JSON.parse(this.stream_token);
}
};
</script>
As you can see in my component, I need three variables:
Fields (array of all fields)
An unique token for a specific resource
The current active field id (so I can set the is-active class).
In my Laravel view file, I use the component like this:
show.blade.php
<editor-navigation fields="{{ json_encode($stream->fields) }}" active="{{ json_encode($field->id) }}" stream_token="{{ json_encode($field->stream->token) }}"></editor-navigation>
So above code works fine, however it feels a bit "messy" - since I need to use the editor-navigation component in a lot of pages, and I am wondering what will happen as soon as I need another variable sent to it - I have to update it in all places.

Ember Js computed property in component fails when observing object property in service

Have an interesting problem in Ember js.
Here below is the component advanced-search/component.js with two computed properties roomType & room dependent on the service services/advanced-search queryObj.{roomId,roomTypeId} object properties.
The roomType computed property fires and updates the template correctly when an option is selected from the template. However, interestingly, the room computed property fails to fire when a room is selected from the template. This I verified by putting a console.log('checking room computed fired') inside the room computed property.
To explore this anomaly further, I did the following:
I uncommented the code you see in the init method that sets the rooms array which populates the room list dropdown and commented the code in the actions hash inside the setRoomType action method that was initially setting the rooms array. After these changes, the room computed property fires correctly and updates the template.
I noticed the array returned by the this.get('store).findAll('roomType') resulted in the roomType computed property to fire correctly and update the template, so I attempted to change the call for rooms inside setRoomType from roomType.get('rooms') to this.get('store') to see if it also resulted in the room computed property to fire correctly but it still did NOT fire the room computed property. So, I concluded that both the roomType and room computed properties could only fire and update the template correctly if their dropdown list arrays were set in the component's init method.
advanced-search/component.js
export default Ember.Component.extend({
advancedSearch: Ember.inject.service('advanced-search'),
queryObj: Ember.computed.alias('advancedSearch.queryObj'),
init() {
this._super(...arguments);
// I believe because the 'roomTypes` array is set in this init method, the 'roomType' computed property fires correctly and updates the template
this.get('store').findAll('roomtype').then((roomTypes) => {
this.set('roomTypes', roomTypes);
});
// When the 'rooms' array is also initialized here, the 'room' computed property fires successfully on 'room' selection from the dropdown and updates the template
// this.get('store').findAll('room').then((rooms) => {
// this.set('rooms', rooms);
// });
},
roomTypes: [],
roomType: Ember.computed('queryObj.{roomTypeId}', function() {
var that = this;
return this.get('roomTypes').find(function(roomType) {
return that.get('queryObj').roomTypeId === roomType.id;
});
}),
rooms: [],
room: Ember.computed('queryObj.{roomId}', function() {
console.log('checking room computed fired')
var that = this;
return this.get('rooms').find(function(room) {
return that.get('queryObj').roomId === room.id;
});
}),
actions: {
setRoomType(roomType) {
this.get('advancedSearch').setRoomType(roomType);
this.set('room', null);
if (roomType) {
// When rooms array initialized from here the room computed property fails to fire on room selection from drop down
roomType.get('rooms').then((rooms) => {
this.set('rooms', rooms);
});
} else {
this.set('rooms', null);
}
},
setRoom(room) {
this.get('advancedSearch').setRoom(room);
}
}});
Here below is the service code:
services/advanced-search
export default Ember.Service.extend({
queryObj: {},
setRoomType(roomType) {
this.set('queryObj.roomTypeId', roomType.id);
},
setRoom(room) {
this.set('queryObj.roomId', room.id);
}});
Here below is the component template:
advanced-search/template.hbs
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3>Advanced Search</h3>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-2">
{{#power-select placeholder="Room type" allowClear=true selected=roomType options=roomTypes onchange=(action "setRoomType") as |roomType| }} {{roomType.name}} {{/power-select}}
</div>
<div class="col-md-2">
{{#power-select placeholder="Room No" allowClear=true selected=room options=rooms onchange=(action "setRoom") as |room| }} {{room.name}} {{/power-select}}
</div>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
NB: My desire is for the 'rooms' property to be set from the action method 'setRoomType' through the 'roomType' model's relationship property called 'rooms' so that the rooms are always filtered according to the 'roomType' selected.
Your help will be greatly appreciated.
Ember Version:
Ember Inspector 2.0.4
Ember 2.8.2
Ember Data 2.9.0
jQuery 3.1.1
Ember Simple Auth 1.1.0
You should not set the computed properties like this.set('room', null); This line of code is the culprit i guess.Once you set computed properties like this then this computed property will not fire again.
What you might need is room computed property with get and set. refer setting computed properties guide
test:Ember.computed('dependantKey',{
get(key){
return 'result';
},
set(key,value){
return value;
}
})

VueJs: How to Edit an Array Item

Simple Todo-App. Please excuse my ignorance for making a rather basic question.
But how would you go about and edit a certain item on an array?
Normally I would try to bind the value of my input to a new property on my data object and then assign this new property to the old property on click throuch Vue's two way databinding.
Like this: http://jsfiddle.net/z7960up7/
Well in my case I use the v-repeat directive, which loops through my data array but I can't use the v-model directive to use the two way databinding, because the values of the properties get corrupted if I do so. (See here: http://jsfiddle.net/doL46etq/2/)
And now I wonder, how I would go about updating my array of tasks:
My idea is to pass the VueObject (this) through my method on click, and then define the index on my event handler and then updating the tasks array, using the index, like this:
HTML:
<input v-el="editInputField" type="text" value="{{ task.body }}" v-on="keyup: doneEdit(this) | key 'enter'"/>
<button v-on="click: editTask(this)">
Edit
</button>
JS:
methods: {
editTask: function (task) {
var taskIndex = this.tasks.indexOf(task.task);
this.tasks[taskIndex] = {
'body': document.querySelector('input').value,
'completed': false
};
console.log(task.task.body);
},
}
Here is my fiddle about it:
http://jsfiddle.net/doL46etq/3/
But the data object is not updated at all and I wonder how I would go about it and update it.
What is the best way to edit an element on the array, using Vue?
Edit: An easy way, would just be to delete the element, and add the new to the array, using the push method, but I really want just to update the element, because I like to keep the dataobject in sync with my backend.
The short answer: Use a component in an extended constructor, then pass the index to that component in HTML as property and use computed properties to link back and forth to your data.
But don't be satisfied with just the short answer. Here is the long one:
Situation: I am using your JSFiddle as base for this answer.
in HTML you have:
<td>{{ task.body }}</td>
<td>
<div>
<input v-el="editInputField" type="text" value="{{ task.body }}" v-on="keyup: doneEdit(this) | key 'enter'" v-model="newEdit"/>
</div>
</td>
<td>
<button v-on="click: editTask(this)" class="mdl-button mdl-js-button mdl-button--icon"> <i class="material-icons">create</i>
</button>
</td>
We want to replace this code with the component. Using this component allows us to identify the index/row we are working on in your set of data.
<td v-component="listitem" index="{{$index}}"></td>
Next step: defining the component.
In order not to cloud our instance with the component, we will create a separate constructor for the vue object, so we can assign the new element to our new object.
This is done using extend.
window.newVue = Vue.extend({
components:
{
'listitem': {
props: ['index'],
computed: {
// both get and set
body: {
get: function () {
return this.$parent.tasks[this.index].body;
},
set: function (v) {
this.$parent.tasks[this.index].body = v
}
}
},
template: '<td>{{ body }}</td><td><div><input type="text" v-model="body" value="{{ body }}"/></div></td><td></td>',
}
}
});
Since we can't define our data properly using an extend, we'll just assume the data already exists while writing the component.
Step 3: defining the actual data:
Instead of using Vue as our object constructor, we'll now use our newly created instantiator.
new newVue({
el: '#todoapp',
data: {
tasks: [{
'body': 'Eat breakfast',
'completed': false
}, {
'body': 'Drink milk',
'completed': false
}, {
'body': 'Go to the store',
'completed': false
}],
newTask: '',
},
});
That's it!
In case you couldn't follow what happened: Here's the Fiddle!
PS: More information about the working of these code can be found on vuejs.org
Actually the simplest way to update an array item, is to two-way bind the task body with the v-model directive.
Example:
http://jsfiddle.net/z7960up7/2/
<div id="demo">
{{ message }}
<div class="edit">
<input type="text" v-model="message">
<button v-on="click: editMessage">Edit</button>
</div>
<pre>{{ $data | json }}</pre>
</div>
And fire an event whenever you blur out of the input box or the edit button is hit.
Also hide the input field with css, by using the v-class directive.

How to update data in Meteor using Reactivevar

I have a page with a form. In this form user can add multiple rows with key and values. There is a restriction that the customFields is created on the fly, not from any subscribed collection.
...html
<template name="main">
{{#each customFields}}
<div>
<input type="text" value="{{key}}"/>
<input type="text" style="width: 300px;" value="{{value}}"/>
</div>
{{/each}}
</template
.... router.js
Router.route 'products.add',
path: '/products/add/:_id'
data:
customFields:[]
....products.js
#using customFieldSet as Reactive Var from meteor package
Template.product.created = ->
#customFieldSet = new ReactiveVar([])
Template.product.rendered = ->
self = this
Tracker.autorun ->
arr = self.customFieldSet.get()
self.data.customFields = arr
Template.product.events(
'click .productForm__addField': (e)->
t = Template.instance()
m = t.customFieldSet.get()
console.log t
m.push(
key: ''
value: ''
)
t.customFieldSet.set m
....
The last event will be trigger when I click the button. And it add another row with key and value empty to the page.
Please advise me why I actually see the reactive variable customFieldSet updated, but there is nothing changed dynamically in html.
P/s: I guess customFields is not updated via Iron router.
Basically, you're doing the thing right. However, you shouldn't be assigning the new reactive data to your template's data context, but rather access it directly from your helpers:
Template.product.helpers({
customFileds: function () {
return Template.instance().customFiledsSet.get();
},
});
Now you can use {{customFields}} in your template code and it should work reactively. Just remember that {{this.customFileds}} or {{./customFileds}} will not work in this case.

Categories