How to call the default behavior's method in Polymer 1.0? - behavior

In polymer 1.0 I have a behavior script that defines properties and methods:
<script>
dataBehavior = {
properties: {
data: {
type: Array,
value: null,
observer: 'dataChanged'
}
},
dataChanged: function(newValue, oldValue) {
console.log('default stuff');
}
};
</script>
and a components that uses the behavior:
<dom-module id="my-module">
<template>
</template>
<script>
Polymer({
is: "my-module",
behaviors: [dataBehavior],
dataChanged: function(newValue, oldValue) {
// How to call the dataChanged method from dataBehavior?
// this.super.dataChanged(); <- don't works!
console.log('custom stuff');
}
});
</script>
</dom-module>
When I change the data property the method that was executed is from my-module, so it make "custom stuff". If I remove the dataChanged method in my-module it execute "default stuff".
How can I execute both the default behavior's method and the component's method?
If it is possible I don't want to copy the code from "dataBehavior.dataChanged" to "my-module.dataChanged". I'd like to call the behavior's method inside the component's method; can I use something like "super" to refer the behavior script?
Thank you very much for the answers!

You could also simply call dataBehavior.dataChanged.call(this, newValue, oldValue):
<dom-module id="my-module">
<template>
</template>
<script>
Polymer({
is: "my-module",
behaviors: [dataBehavior],
dataChanged: function(newValue, oldValue) {
dataBehavior.dataChanged.call(this, newValue, oldValue)
}
});
</script>
</dom-module>

I don't think this is possible. The only solution I have is that you set up an observer that calls a "super" function that executes and then calls another function which is "abstract":
<script>
dataBehavior = {
properties: {
data: {
type: Array,
value: null,
observer: 'superDataChanged'
}
},
superDataChanged: function(newValue, oldValue) {
console.log('default stuff');
this.abstractDataChanged(newValue, oldValue);
},
abstractDataChanged: function (newValue, oldValue) {
// abstract
}
};
</script>
Your element(s) can then implement this abstract method to do specific things:
<dom-module id="my-module">
<template>
</template>
<script>
Polymer({
is: "my-module",
behaviors: [dataBehavior],
abstractDataChanged: function(newValue, oldValue) {
console.log('custom stuff');
}
});
</script>
</dom-module>
When this is run, you will see the following output:
default stuff
custom stuff
Watch this video from the Polycasts series that explains how to create and implement behaviors. It also covers abstract methods.
I've set up a Plunker here. When you click the 'click me' text, this triggers a function which changes the array value so that the observer function is called.

Thank you very much #Ben for the answer, that is a good solution to solve the problem.
A new idea from your solution is that I could choose to completely override the default method or use it where I want, in this way:
<script>
dataBehavior = {
properties: {
data: {
type: Array,
value: null,
observer: 'dataChanged'
}
},
dataChanged: function(newValue, oldValue) {
this.superDataChanged(newValue, oldValue);
},
superDataChanged: function(newValue, oldValue) {
console.log('default stuff');
}
};
</script>
Using the standard "dataChanged" method that calls the "superDataChanged" method the component will be:
<dom-module id="my-module">
<template>
</template>
<script>
Polymer({
is: "my-module",
behaviors: [dataBehavior],
dataChanged: function(newValue, oldValue) {
// this line here to call the default method at the start:
this.superDataChanged(newValue, oldValue);
// ONLY this line to NOT execute the default method
console.log('custom stuff');
// this line here to call the default method at the end:
this.superDataChanged(newValue, oldValue);
}
});
</script>
</dom-module>
In this way I could choose what to do with the "default stuff".

Related

vue not loading data into child component

I've a hard time in understanding the methods of vue. In my put-request users can edit, delete images. In parent component the get-request loads the images and the are pushed to an image-gallery (the child-component) via properties. In my set up the console.log is always empty.
//PARENT COMPONENT
<template>
<div class="form-group">
<image-gallery :serverData="serverMap"/>
</div>
</template>
<script>
import ImageGallery from './ImageGallery.vue';
export default {
components:{ImageGallery},
data: () => ({
serverMap: {
title: '',
file: ''
}
}),
mounted () {
//AJAX ETC get servermap
.then((response) => {
this.serverMap = response.data
})
}
Just a normal straight parent-child situation. Here under the child-component
<template>
</template>
<script>
export default {
name: 'ImageGallery',
//incoming data
props: {
serverData: {
type: Object,
default () {
return {
hasLabels: true,
isHorizontal: false
}
}
}
},
created: function () {
this.loadImages()
},
methods: {
loadImages () {
console.log(this.serverData.file)
//do something with the serverData
//prepare for fileReader function
//together with new image validation
}
}
The method 'loadImages' should be automatically delevering the serverData via computed.But is doesn t. Who can help?
There is race condition.
Either not render a child until data is available; serverMap needs to be null instead of empty object in order to be distinguished from populated object:
<image-gallery v-if="serverMap" :serverData="serverMap"/>
Or delay data access in a child until it's available instead of doing this immediately in created:
watch: {
serverData(data) {
if (data)
this.loadImages()
}
}

Vue.JS not update data into nested Component

I'm working with 3 VUE nested components (main, parent and child) and I'm getting trouble passing data.
The main component useget a simple API data based on input request: the result is used to get other info in other component.
For example first API return the regione "DE", the first component is populated then try to get the "recipes" from region "DE" but something goes wrong: The debug comments in console are in bad order and the variable used results empty in the second request (step3):
app.js:2878 Step_1: DE
app.js:3114 Step_3: 0
app.js:2890 Step_2: DE
This is the parent (included in main component) code:
parent template:
<template>
<div>
<recipes :region="region"/>
</div>
</template>
parent code:
data: function () {
return {
region: null,
}
},
beforeRouteEnter(to, from, next) {
getData(to.params.e_title, (err, data) => {
console.log("Step_1: "+data.region); // return Step_1: DE
// here I ned to update the region value to "DE"
next(vm => vm.setRegionData(err, data));
});
},
methods: {
setRegionData(err, data) {
if (err) {
this.error = err.toString();
} else {
console.log("Step_2: " + data.region); // return DE
this.region = data.region;
}
}
},
child template:
<template>
<div v-if="recipes" class="content">
<div class="row">
<recipe-comp v-for="(recipe, index) in recipes" :key="index" :title="recipe.title" :vote="recipe.votes">
</recipe-comp>
</div>
</div>
</template>
child code:
props: ['region'],
....
beforeMount () {
console.log("Step_3 "+this.region); // Return null!!
this.fetchData()
},
The issue should be into parent beforeRouteEnter hook I think.
Important debug notes:
1) It looks like the child code works properly because if I replace the default value in parent data to 'IT' instead of null the child component returns the correct recipes from second API request. This confirms the default data is updated too late and not when it got results from first API request.
data: function () {
return {
region: 'IT',
}
},
2) If I use {{region}} in child template it shows the correct (and updated) data: 'DE'!
I need fresh eyes to fix it. Can you help me?
Instead of using the beforeMount hook inside of the child component, you should be able to accomplish this using the watch property. I believe this is happening because the beforeMount hook is fired before the parent is able to set that property.
More on the Vue lifecycle can be found here
More on the beforeMount lifecycle hook can be found here
In short, you can try changing this:
props: ['region'],
....
beforeMount () {
console.log("Step_3 "+this.region); // Return null!!
this.fetchData()
},
To something like this:
props: ['region'],
....
watch: {
region() {
console.log("Step_3 "+this.region); // Return null!!
this.fetchData()
}
},
Cheers!!

Vue JS: this.$on event doesn't contain passed parameters

Here are my components. I've successfully emitted parameters from the child component to the parent, but not from the parent to the child. The console.log('In initDetail()'); line fires, which means the $on event is triggered, but param is undefined. I'm wondering why.
Parent component:
components: {
"child-component": ChildComponent
}
methods: {
loadDetail() {
this.$emit('loadDetailEvent', 'test');
}
}
Child Component:
mounted() {
this.$on('loadDetailEvent', this.initDetail(param));
}
methods: {
initDetail(param) {
console.log('In initDetail()');
console.log(param);
}
}
I've also tried calling a function right away. Neither the console.log('$on event'); nor the console.log(param); lines print.
this.$on('loadDetailEvent', function(param){
console.log('$on event');
console.log(param);
});
As pointed out in the comments, there are a couple misconceptions in your code:
Your parent component is emitting a loadDetailEvent event when the loadDetail method is called. Your child component is also listening for a loadDetailEvent event, but it will only handle this event if it is emitted by its own Vue instance. If the Vue instance of the parent emits an event, the child will have no knowledge of it.
You are attempting to handle the loadDetailEvent by firing initDetail and passing the parameters of the event to that method. But, in your code you are simply setting the loadDetailEvent handler to be the result of calling this.initDetail(param) within the scope of the mounted hook. What you would want to do in this case would be to specify an anonymous function as the handler, which receives the param value and passes it to this.initDetail:
this.$on('loadDetailEvent', (param) => this.initDetail(param))
But, to get at the root of your issue: it seems like you want to call a child method when a parent method is called. You could do this a few different ways:
As #Ohgodwhy suggested, you could create a separate, global Vue instance to use as an event bus.
You could set a ref (say ref="child") on the child component tag in your parent's template and then call the child component's method directly via this.$refs.child.initDetail('test').
As #B.Fleming suggested, you could set a watcher on the child component to react to a changing prop value passed by the parent component. This gets a little tricky since you would need to maintain the value of the variable being passed as the prop (I would use a .sync modifier, as you can see below).
Here are example snippets of the above solutions:
Using an event bus:
let EventBus = new Vue();
Vue.component('child', {
template: `<div>Child</div>`,
mounted() {
EventBus.$on('loadDetailEvent', (param) => this.initDetail(param));
},
methods: {
initDetail(param) {
console.log('In initDetail()');
console.log(param);
}
}
});
new Vue({
el: '#app',
methods: {
loadDetail() {
EventBus.$emit('loadDetailEvent', 'test');
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<child></child>
<button #click="loadDetail">load</button>
</div>
Using a ref:
Vue.component('child', {
template: `<div>Child</div>`,
methods: {
initDetail(param) {
console.log('In initDetail()');
console.log(param);
}
}
});
new Vue({
el: '#app',
methods: {
loadDetail() {
this.$refs.child.initDetail('test');
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<child ref="child"></child>
<button #click="loadDetail">load</button>
</div>
Using a prop value and a watcher:
Vue.component('child', {
template: `<div>Child</div>`,
props: { loading: String },
methods: {
initDetail(param) {
console.log('In initDetail()');
console.log(param);
}
},
watch: {
loading(val) {
if (val) {
this.initDetail(val);
this.$emit('update:loading', '');
}
}
}
});
new Vue({
el: '#app',
data() {
return { payload: '' }
},
methods: {
loadDetail() {
this.payload = 'test';
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<child :loading.sync="payload"></child>
<button #click="loadDetail">load</button>
</div>

polymer 1.0 event firing among nested components

I have a problem in Polymer 1.0 related to event propagation within a nested structure of web components. In particular, I am trying to dynamically configure a web component named wc-split by means of a collection of other components named wc-split-rule located within its local DOM. The following snippet of code shows a correct form of use:
<wc-split-test>
<wc-split>
<wc-split-rule key="{{k1}}" ...></wc-split-rule>
<wc-split-rule key="{{k2}}" ...></wc-split-rule>
<wc-split-rule key="{{k3}}" ...></wc-split-rule>
</wc-split>
</wc-split-test>
As it can be seen in the previous example, the aim is to provide to the wc-split component the values on key attributes within each wc-split-rule component. As we need dynamic reconfiguration capabilities, the architectural strategy starts by firing an event each time a change in key attributes is met and those changes are promoted by bubbling up to reach the wc-split component, which process them.
The followed approach works properly when [1] it is both tested in a pure HTML context with literal values and [2] within a component template with data-bound values. Nevertheless, [3] when it is tested within a component template using literal values, changes are not promoted. It seems that event propagation are ignored or listener defined in wc-split does not catch the event:
<wc-split-test>
<wc-split> <!-- does not work -->
<wc-split-rule key="k1" ...></wc-split-rule>
<wc-split-rule key="k2" ...></wc-split-rule>
<wc-split-rule key="k3" ...></wc-split-rule>
</wc-split>
</wc-split-test>
The following listing shows implementation of both components [https://goo.gl/OkU9jQ]:
<dom-module id="wc-split-rule">
<script>
Polymer({
is: 'wc-split-rule',
properties: {
key : {
type: String,
reflectToAttribute: true,
notify: true,
value: '',
observer: '_changed'
},
},
_changed: function (){
this.fire('wc-split-rule', {
key : this.key,
});
}
});
</script>
</dom-module>
<dom-module id="wc-split">
<template>
<content></content>
</template>
<script>
Polymer( {
is: 'wc-split',
listeners: {
'wc-split-rule': 'onRule'
},
ready: function(){
...
},
onRule: function (event, context){
... // this is executed in test [1] and [2] NOT in [3]
}
});
</script>
</dom-module>
<dom-module id="wc-split-test">
<template>
<wc-split id="split">
<wc-split-rule key="e1"/>
</wc-split>
</template>
<script>
...
</script>
</dom-module>
Surprisingly, the same code on Polymer 0.5 works properly for each test scenario [https://goo.gl/CHV3JE]:
<polymer-element name="wc-split-rule">
<script>
Polymer('wc-split-rule', {
publish : {
key : '',
},
observe: {
key : '_changed',
},
_changed: function (){
this.fire('wc-split-rule', {
key : this.key,
});
}
});
</script>
</polymer-element>
<polymer-element name="wc-split">
<template>
<div on-wc-split-rule="{{onRule}}">
<content select="wc-split-rule"></content>
</div>
<content></content>
</template>
<script>
Polymer('wc-split', {
ready: function(){
...
},
onRule: function (event, context){
... // this is always executed
}
});
</script>
</polymer-element>
<polymer-element name="wc-split-test">
<template>
<wc-split id="split">
<wc-split-rule key="e1"/>
</wc-split>
</template>
<script>
...
</script>
</polymer-element>
This boils down to a timing issue. The wc-split-rule event is firing before your wc-split element is registered. Therefore, the event is being missed. It's only an issue when the elements are first booted up b/c you have a parent element that's also a custom element. One way around this is to ensure the event fires after the wc-split-rule is attached:
attached: function() {
this._changed();
},
This works: http://jsbin.com/yixinuhahu/edit?html,output

canjs component tempate dom live binding

My code is to realize a paginate page like this example, https://github.com/bitovi/canjs/blob/master/component/examples/paginate.html .
I found the {#messages}...{/messages} in message.mustache template was not been inserted into page , while messagelist component inserted event has been triggered, so i can not do any binding to {#messages} dom in the event, because it ‘not exists in the page.
Are there other ways to fix this problem?
The Templates:
message_list.mustache:
<app>
<messagelist deferredData='messagesDeferred'></messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>
message.mustache:
{#messages}}
<dl>
<dt>.....</dt>
<dd>....</dd>
</dl>
{/messages}
The Component:
can.Component.extend({
tag: "messagelist",
template: can.view('/static/web/tpl/mobile/message.mustache'), // to load message template
scope: {
messages: [],
waiting: true,
},
events: {
init: function () {
this.update();
},
"{scope} deferreddata": "update",
update: function () {
var deferred = this.scope.attr('deferreddata'),
scope = this.scope,
el = this.element;
if (can.isDeferred(deferred)) {
this.scope.attr("waiting", true);
deferred.then(function (messages) {
scope.attr('messages').replace(messages);
});
} else {
scope.attr('messages').attr(deferred, true);
}
},
"{messages} change": function () {
this.scope.attr("waiting", false);
},
inserted: function(){
// can't operate the dom in message.mustache template
}
}
});
//to load component template
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
$("#message-list").html(content)
});
I have solved the problem, but not the best, Maybe someone have a better way.
I changed my template, add a new component called <messageitem>
<messageitem> will load another template: message.mustache
Every <messageitem> will trigger inserted event when inserted into <messagelist>
The new component:
can.Component.extend({
tag: "messageitem",
template:can.view('/static/web/tpl/mobile/message.mustache'),
events: {
inserted: function(el, ev){
// Can-click can not satisfy my needs,
// because i call the third-party module to bind click event
// this module will be called repeatedly, not the best way
reloadModules(['accordion']);
}
}
});
// To load message_list.mustache
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
$("#message-list").html(content)});
Static html:
<body>
<div id="message-list">
....
</div>
</body>
message_list.mustache:
<app>
<messagelist deferredData='messagesDeferred'>
{{#messages}}
<messageitem></messageitem>
{{/messages}}
</messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>
message.mustache:
<dl class="am-accordion-item" >
...
</dl>

Resources