I've tried to count how many directives are used on a component like this. But it does not work as I expected
this is my directive file
import ahoy from "ahoy.js"
let count = 0
export default {
id: "bar",
definition: {
bind: (el, binding) => {
const handler = (entries, observer) => {
count++
console.log(count)
if (entries[0].isIntersecting) {
setTimeout(() => {
ahoy.track("impression", {
...(typeof binding.value === "object"
? { ...binding.value }
: { value: binding.value }),
page: document.title,
path: window.location.pathname.replace(/^\/en\//g, "/"),
class: el.classList.value
})
observer.unobserve(entries[0].target)
}, 100)
}
}
const createIntersection = new IntersectionObserver(handler, { rootMargin: "-45% 0%" })
createIntersection.observe(el)
}
}
}
and this is how I call directive on my component
ReviewCard(
v-bar="createIntersection(foo)"
)
variable count not stored val++
how can I count how many directives are used on a component?
Thanks in advance :)
count++ is currently in handler, which is passed to the IntersectionObserver, so count would only be incremented upon an intersection. That update should probably be moved outside of handler to the root of the bind() call:
export default {
definition: {
bind: (el, binding) => {
count++
const handler = /*...*/
//...
}
}
}
Related
I'm having lots of elements on which #mouseenter set a value to true and #mouseleave sets it to false. Basically what I need is a way to set a reactive variable to true if the mouse hovers the element.
I've been trying to figure out how to write such custom directive from the docs but it only mentions how to use .focus() js function on an element. Which js functions would be used for said directive?
Something like:
const vHover = {
mounted: (el) => {
el.addEventListener('mouseenter', state.hover=true)
el.addEventListener('mouseleave', state.hover=false)
}
}
I think you could do something like:
app.directive('hover', {
created(el, binding) {
const callback = binding.value
el.onmouseenter = () => callback(true)
el.onmouseleave = () => callback(false)
},
unmounted(el) {
el.onmouseenter = null
el.onmouseleave = null
}
})
Template:
<button v-hover="onHoverChange">Example</button>
Methods:
onHoverChange(isHovered) {
console.log(isHovered)
}
I believe this is not the intended use of directives. The value of the state cannot be mutated within the directive. You can pass the variable through the binding, but you cannot update it.
binding: an object containing the following properties.
value: The value passed to the directive. For example in v-my-directive="1 + 1", the value would be 2.
oldValue: The previous value, only available in beforeUpdate and updated. It is available whether or not the value has changed.
so if you do el.addEventListener('mouseenter', binding.hover=true), as you may have noticed, it will not update the state.
However, if we use the internals (PSA: though not recommended since they could potentially change at any time), you could get instance using the vnode, and use the binding.arg to denote which Proxy (state)
so you could get the reactive variable with vnode.el.__vueParentComponent.data[binding.arg]
<script>
export default {
data(){
return {
state: { hover:false }
}
},
directives: {
hover: {
mounted(el, binding, vnode) {
el.addEventListener('mouseenter', () => {
vnode.el.__vueParentComponent.data[binding.arg].hover = true
})
el.addEventListener('mouseleave', () => {
vnode.el.__vueParentComponent.data[binding.arg].hover = false
})
},
}
}
}
</script>
<template>
<h1 v-hover:state="state">HOVER {{ state }}</h1>
</template>
SFC playground link
of course you might want to add the unmounted and even consider adding mouseleave dynamically only when mouseenter fires
This is how it can be done inside the component:
const vHover = {
mounted: (el) => {
el.addEventListener('mouseenter', () => {state.hover=true})
el.addEventListener('mouseleave', () => {state.hover=false})
},
unmount: (el) => {
el.removeEventListener('mouseenter', () => {state.hover=true})
el.removeEventListener('mouseleave', () => {state.hover=false})
}
}
I want to design one custom directive to replace 'cx' to <strong>cx</strong> for all TextNodes in the Dom Tree.
Below is what I had tried so far:
Vue.config.productionTip = false
function removeKeywords(el, keyword){
if(!keyword) return
let n = null
let founds = []
walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false)
while(n=walk.nextNode()) {
if(n.textContent.trim().length < 1) continue
founds.push(n)
}
let result = []
founds.forEach((item) => {
if( new RegExp('cx', 'ig').test(item.textContent) ) {
let kNode = document.createElement('span')
kNode.innerHTML = item.textContent.replace(new RegExp('(.*?)(cx)(.*?)', 'ig'), '$1<strong>$2</strong>$3')
item.parentNode.insertBefore(kNode, item)
item.parentNode.removeChild(item)
}
})
}
let myDirective = {}
myDirective.install = function install(Vue) {
let timeoutIDs = {}
Vue.directive('keyword-highlight', {
bind: function bind(el, binding, vnode) {
clearTimeout(timeoutIDs[binding.value.id])
if(!binding.value) return
timeoutIDs[binding.value.id] = setTimeout(() => {
removeKeywords(el, binding.value.keyword)
}, 500)
},
componentUpdated: function componentUpdated(el, binding, vnode) {
clearTimeout(timeoutIDs[binding.value.id])
timeoutIDs[binding.value.id] = setTimeout(() => {
removeKeywords(el, binding.value.keyword)
}, 500)
}
});
};
Vue.use(myDirective)
app = new Vue({
el: "#app",
data: {
keyword: 'abc',
keyword1: 'xyz'
},
methods: {
}
})
.header {
background-color:red;
}
strong {
background-color:yellow
}
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<input v-model="keyword">
<input v-model="keyword1">
<h1>Test Case 1: try to change 2nd input to <span class="header">anything</span></h1>
<div v-keyword-highlight="{keyword:keyword, id:1}">
<p>Test1<span>Test2</span>Test3<span>{{keyword}}{{keyword1}}</span></p>
</div>
<h1>Test Case 2 which is working</h1>
<div :key="keyword+keyword1" v-keyword-highlight="{keyword:keyword, id:2}">
<p>Test1<span>Test2</span>Test3<span>{{keyword}}{{keyword1}}</span></p>
</div>
</div>
First Case: It should be caused by related VNode already been replaced by <span><strong></strong></span>, so will not get updated with the data properties correctly.
Second Case: It works as expected. The solution is added :key to force mount the component, so when update is triggered, it will render with the template and latest data properties then mount.
But I prefer to force mount in the directive hook instead of bind :key at the component, or get the updated Dom($el) based on the template and the latest data properties. so anyone else who want to use this directive doesn't need to case about the :key.
Many thanks for any.
I'm not sure this is the best practice since there are warnings against modifying vnode, but this works in your sample to dynamically add the key
vnode.key = vnode.elm.innerText
The weird thing I notice that the first directive responds to componentUpdated but the second does not, even though the second inner elements update their values but the first does not - which is contrary to what you would expect.
Note that the change occurs because the second instance calls bind again when the inputs change, not because of the code in componentUpdated.
console.clear()
Vue.config.productionTip = false
function removeKeywords(el, keyword){
console.log(el, keyword)
if(!keyword) return
let n = null
let founds = []
walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false)
while(n=walk.nextNode()) {
if(n.textContent.trim().length < 1) continue
founds.push(n)
}
let result = []
founds.forEach((item) => {
if( new RegExp('cx', 'ig').test(item.textContent) ) {
let kNode = document.createElement('span')
kNode.innerHTML = item.textContent.replace(new RegExp('(.*?)(cx)(.*?)', 'ig'), '$1<strong>$2</strong>$3')
item.parentNode.insertBefore(kNode, item)
item.parentNode.removeChild(item)
}
})
}
let myDirective = {}
myDirective.install = function install(Vue) {
let timeoutIDs = {}
Vue.directive('keyword-highlight', {
bind: function bind(el, binding, vnode) {
console.log('bind', binding.value.id)
clearTimeout(timeoutIDs[binding.value.id])
if(!binding.value) return
vnode.key = vnode.elm.innerText
timeoutIDs[binding.value.id] = setTimeout(() => {
removeKeywords(el, binding.value.keyword)
}, 500)
},
componentUpdated: function componentUpdated(el, binding, vnode) {
//clearTimeout(timeoutIDs[binding.value.id])
//timeoutIDs[binding.value.id] = setTimeout(() => {
//removeKeywords(el, binding.value.keyword)
//}, 500)
}
});
};
Vue.use(myDirective)
app = new Vue({
el: "#app",
data: {
keyword: 'abc',
keyword1: 'xyz'
},
methods: {
}
})
.header {
background-color:red;
}
strong {
background-color:yellow
}
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<input v-model="keyword">
<input v-model="keyword1">
<h1>Test Case 1: try to change 2nd input to <span class="header">anything</span></h1>
<div v-keyword-highlight="{keyword:keyword, id:1}">
<p>Test1<span>Test2</span>Test3<span>{{keyword}}{{keyword1}}</span></p>
</div>
<h1>Test Case 2 which is working</h1>
<div :key="keyword+keyword1" v-keyword-highlight.keyword1="{keyword:keyword, id:2}">
<p>Test1<span>Test2</span>Test3<span>{{keyword}}{{keyword1}}</span></p>
</div>
</div>
I found Vue uses Vue.patch to compare old/new nodes then generate out Dom elements.
Check Vue Github Lifecycle source code, so the first element can be one Dom object which will be mounted.
So I follow the steps to uses the third parameter of the directive hooks (bind, componentUpdated, update etc) to generate new Dom elements, then copy it to the first parameter of the directive hooks.
Finally below demo seems work: no force re-mount, only re-compile VNodes.
PS: I uses deepClone methods to clone vnode because inside of the function __patch__(oldNode, newNode, hydrating), it will modify newNode.
PS: As Vue directive access its instance said, inside the hooks of the directive, uses vnode.context to access the instance.
Edit: loop all childrens under test, then append to el, simple copy test.innerHTML to el.innerHTML will cause some issues like the button is not working.
Then test this directive in my actual project like <div v-keyword-highlight>very complicated template</div>, it is working fine so far.
function deepClone (vnodes, createElement) {
let clonedProperties = ['text', 'isComment', 'componentOptions', 'elm', 'context', 'ns', 'isStatic', 'key']
function cloneVNode (vnode) {
let clonedChildren = vnode.children && vnode.children.map(cloneVNode)
let cloned = createElement(vnode.tag, vnode.data, clonedChildren)
clonedProperties.forEach(function (item) {
cloned[item] = vnode[item]
})
return cloned
}
return vnodes.map(cloneVNode)
}
function addStylesForKeywords(el, keyword){
if(!keyword) return
let n = null
let founds = []
walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false)
while(n=walk.nextNode()) {
if(n.textContent.trim().length < 1) continue
founds.push(n)
}
let result = []
founds.forEach((item) => {
if( new RegExp('cx', 'ig').test(item.textContent) ) {
let kNode = document.createElement('span')
kNode.innerHTML = item.textContent.replace(new RegExp('(.*?)(cx)(.*?)', 'ig'), '$1<strong>$2</strong>$3')
item.parentNode.insertBefore(kNode, item)
item.parentNode.removeChild(item)
}
})
}
let myDirective = {}
myDirective.install = function install(Vue) {
let timeoutIDs = {}
let temp = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>'
})
let fakeVue = new temp()
Vue.directive('keyword-highlight', {
bind: function bind(el, binding, vnode) {
clearTimeout(timeoutIDs[binding.value.id])
if(!binding.value) return
timeoutIDs[binding.value.id] = setTimeout(() => {
addStylesForKeywords(el, binding.value.keyword)
}, 500)
},
componentUpdated: function componentUpdated(el, binding, vnode) {
let fakeELement = document.createElement('div')
//vnode is readonly, but method=__patch__(orgNode, newNode) will load new dom into the second parameter=newNode.$el, so uses the cloned one instead
let clonedNewNode = deepClone([vnode], vnode.context.$createElement)[0]
let test = clonedNewNode.context.__patch__(fakeELement, clonedNewNode)
while (el.firstChild) {
el.removeChild(el.firstChild);
}
test.childNodes.forEach((item) => {
el.appendChild(item)
})
clearTimeout(timeoutIDs[binding.value.id])
timeoutIDs[binding.value.id] = setTimeout(() => {
addStylesForKeywords(el, binding.value.keyword)
}, 500)
}
});
};
Vue.use(myDirective)
Vue.config.productionTip = false
app = new Vue({
el: "#app",
data: {
keyword: 'abc',
keyword1: 'xyz'
},
methods: {
changeData: function () {
this.keyword += 'c'
this.keyword1 = 'x' + this.keyword1
console.log('test')
}
}
})
.header {
background-color:red;
}
strong {
background-color:yellow
}
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<script src="https://unpkg.com/lodash"></script>
<div id="app">
<input v-model="keyword">
<input v-model="keyword1">
<h4>Test Case 3 <span class="header"></span></h4>
<div v-keyword-highlight="{keyword:keyword, id:1}">
<p>Test1<span>Test2</span>Test3<span>{{keyword}}{{keyword1}}</span></p>
<button #click="changeData()">Click me</button>
</div>
</div>
I have a working piece of code as below:
let pageParams = {
data: { todos: [], desc: '' }
}
pageParams.onLoad = function () {
//I am trying to encapsulate this to a standalone function and
// make it generic, instead of hard coding the 'this.addTodo=XXX'
const evProducer = {
start: listener => {
//Here, I am adding a named property function
this.addTodo = ev => {
listener.next(ev.detail.value)
}
},
stop: ()=>{}
}
const input$ = xs.create(evProducer)
input$.compose(debounce(400)).subscribe({
next: val => console.log(val)
})
}
The code works and now I am going to do some refactor work, i.e. move the logic out of this onLoad function. So I move the logic to another module
let xsCreator = {}
xsCreator.fromEvent = function(handler){
const evProducer = {
start: listener => {
handler = ev => listener.next(ev.detail.value)
},
stop: () => {}
}
return xs.create(evProducer)
}
And in the previous onLoad function becomes the following:
pageParams.onLoad = function () {
xs.fromEvent(this.addTodo).subscribe(blablabla)
}
but it does not work. I guess I might use apply/call/bind to make this work, but don't know how to. Anyone can help? Thanks in advance
I've found the solution, I should use Object.defineProperty to add a named property for object.
xsCreator.fromInputEvent = (srcObj, propertyName) => {
const evProducer = {
start: (listener) => {
Object.defineProperty(
srcObj,
propertyName,
{value: ev => listener.next(ev.detail.value)})
},
stop: () => {}
}
return xs.create(evProducer)
}
I'm employing the suggestion from #gaearon to setup a listener on my redux store. I'm using this format:
function observeStore(store, select, onChange) {
let currentState;
if (!Function.prototype.isPrototypeOf(select)) {
select = (state) => state;
}
function handleChange() {
let nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState);
}
}
let unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
I'm using this in an onEnter handler for a react-router route:
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
const disposeRouteHandler = observeStore(store, null, (state) => {
const conditions = [
isLoaded(state.thing1),
isLoaded(state.thing2),
isLoaded(state.thing3),
];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
// I'm done: how do I dispose the store subscription???
}
});
store.dispatch(
entities.getOrCreate({
entitiesState: store.getState().entities,
nextState,
})
);
};
};
Basically this helps gate the progression of the router while actions are finishing dispatching (async).
My problem is that I can't figure out where to call disposeRouteHandler(). If I call it right after the definition, my onChange function never gets a chance to do it's thing, and I can't put it inside the onChange function because it's not defined yet.
Appears to me to be a chicken-egg problem. Would really appreciate any help/guidance/insight.
How about:
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
let shouldDispose = false;
const disposeRouteHandler = observeStore(store, null, (state) => {
const conditions = [
isLoaded(state.thing1),
isLoaded(state.thing2),
isLoaded(state.thing3),
];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
if (disposeRouteHandler) {
disposeRouteHandler();
} else {
shouldDispose = true;
}
}
});
if (shouldDispose) {
disposeRouteHandler();
}
store.dispatch(
entities.getOrCreate({
entitiesState: store.getState().entities,
nextState,
})
);
};
};
Even though using the observable pattern leads to some buy-in, you can work around any difficulties with normal js code. Alternatively you can modify your observable to suit your needs better.
For instance:
function observeStore(store, select, onChange) {
let currentState, unsubscribe;
if (!Function.prototype.isPrototypeOf(select)) {
select = (state) => state;
}
function handleChange() {
let nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState, unsubscribe);
}
}
unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
and
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
const disposeRouteHandler = observeStore(store, null, (state, disposeRouteHandler) => {
const conditions = [
isLoaded(state.thing1),
isLoaded(state.thing2),
isLoaded(state.thing3),
];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
disposeRouteHandler();
}
}
store.dispatch(
entities.getOrCreate({
entitiesState: store.getState().entities,
nextState,
})
);
};
};
It does add a strange argument to onChange but it's just one of many ways to do it.
The core problem is that handleChange gets called synchronously immediately when nothing has changed yet and asynchronously later. It's known as Zalgo.
Inspired by the suggestion from #DDS, I came up with the following alteration to the other pattern mentioned in #gaearon's comment:
export function toObservable(store) {
return {
subscribe({ onNext }) {
let dispose = this.dispose = store.subscribe(() => {
onNext.bind(this)(store.getState())
});
onNext.bind(this)(store.getState());
return { dispose };
},
dispose: function() {},
}
}
This allows me to invoke like:
Entity.onEnter = function makeFetchEntity(store) {
return function fetchEntity(nextState, replace, callback) {
toObservable(store).subscribe({
onNext: function onNext(state) {
const conditions = [/* many conditions */];
if (conditions.every((test) => !!test) {
callback(); // allow react-router to complete routing
this.dispose(); // remove the store subscription
}
},
});
store.dispatch(/* action */);
};
};
The key difference is that I'm passing a regular function in for onNext so as not to interfere with my bind(this) in toObservable; I couldn't figure out how to force the binding to use the context I wanted.
This solution avoids
add[ing] a strange argument to onChange
... and in my opinion also conveys a bit more intent: this.dispose() is called from within onNext, so it kinda reads like onNext.dispose(), which is exactly what I want to do.
How can I write a really super, simple state changing routine? I need something like Redux, but way simpler, don't need all the bells & whistles.
I was thinking of a global object i.e. myState = {}, that is changed via setMyState() / getMyState().
I'm using JavaScript, and wondering if this would be done via a timer that polls say every 10ms, or so.
So in my JavaScript client app (I'm using ReactJS), a call to my getMyState("show-menu") inside a render() would update the Component's state just like using this.state..
The reason I want this is:
1) Wanna know how to write it for learning purposes.
2) Need something simpler that Redux, simple like Meteor's Session vars, so don't have to pass this.Refs. down to child compnents which setState on parent components.
3) Redux is a mouthful, there is still lots to digest and learn to use Redux.
Seems like you could do this pretty simply with a constructor.
function State () {
this._state = {};
...
}
State.prototype.get = function () {
return this._state;
};
State.prototype.set = function (state) {
return this._state = state;
};
var STATE = new State();
But then you have to do the polling you mentioned in your post. Alternatively, you can look at eventEmitter libraries for javascript, for example https://github.com/facebook/emitter, and turn the State object into an event emitter.
Update
Not sure if this is what you're looking for, at all, but it's simpler.
function makeStore () {
var state = { };
return {
set (key, value) { state[key] = value; },
get (key) { return state[key]; }
};
}
const store = makeStore();
store.set("counter", 1);
store.get("counter"); // 1
Believe it or not, there's really not a lot to Redux.
There's, perhaps, a lot to think about, and it's extra work to keep everything untied from your store...
But have a quick look:
function reducer (state, action) {
state = state || { count: 0 };
const direction = (action.type === "INCREASE") ? 1 : (action.type === "DECREASE") ? -1 : 0;
return {
count: (state.count + direction)
};
}
function announceState () {
console.log(store.getState());
}
function updateView () {
const count = store.getState().count;
document.querySelector("#Output").value = count || 0;
}
function increase () {
store.dispatch({ type: "INCREASE" });
}
function decrease () {
store.dispatch({ type: "DECREASE" });
}
const store = createStore(reducer, { count: 0 });
store.subscribe(announceState)
.subscribe(updateView);
document.querySelector("#Increment").onclick = increase;
document.querySelector("#Decrement").onclick = decrease;
updateView();
This is the code I intend to use.
Looking at it, I'm pretty much just creating a store (with a function to run every time there's an event), there's the subscription to have a listener run, after the store has updated, there's a line where I fire an action, and... ...well, that's it.
function createStore (reduce, initialState) {
var state = initialState;
var listeners = [];
function notifyAll () {
listeners.forEach(update => update());
}
function dispatch (event) {
const newState = reduce(state, event);
state = newState;
notifyAll();
return store;
}
function subscribe (listener) {
listeners.push(listener);
return store;
}
function getState () {
return state;
}
const store = {
getState, subscribe, dispatch
};
return store;
}
// THIS IS MY APPLICATION CODE
function reducer (state, action) {
state = state || { count: 0 };
const direction = (action.type === "INCREASE") ? 1 : (action.type === "DECREASE") ? -1 : 0;
return {
count: (state.count + direction)
};
}
function announceState () {
console.log(store.getState());
}
function updateView () {
const count = store.getState().count;
document.querySelector("#Output").value = count || 0;
}
function increase () {
store.dispatch({ type: "INCREASE" });
}
function decrease () {
store.dispatch({ type: "DECREASE" });
}
const store = createStore(reducer, { count: 0 });
store.subscribe(announceState)
.subscribe(updateView);
document.querySelector("#Increment").onclick = increase;
document.querySelector("#Decrement").onclick = decrease;
updateView();
<button id="Decrement">-</button>
<output id="Output"></output>
<button id="Increment">+</button>
The very tiny, very easy implementation of a store (note that the real thing is more complex) is above. dispatch and subscribe are very useful, here.