Hey , you !


  • Home

  • Archives

Easier Way to Understand apply and call in JS

Posted on 2018-12-04 | In js

The first time I know apply was when I met this code:

Math.max.apply(null, [1, 2, 3, 4])

As the mdn shows, the syntax is:

function.apply( thisArg , [argsArray] )

Actually, in case above, thisArg has no influence which means code below also works:

Math.max.apply(undefined, [1, 2, 3, 4])
Math.max.apply(Math, [1, 2, 3, 4])

The only effect of apply in the code above is that it can pass the values in array to the function max. So, code above equal

Math.max(1, 2, 3, 4)

Why would I mention this? Because we don’t need this anymore because we already have ... which works like:

Math.max(...[1, 2, 3, 4])

The reason that we still need apply and call is the thisArg. They can help us call some powerful methods.

thisArg in apply and call

I guess you might have seen this code:

Array.prototype.slice.call({ length: 2 })
function fn() {
console.log(Array.prototype.slice.call(arguments))
}
fn(1, 2, 3, 4) //[1,2,3,4]

Today, we don’t need this either because of Array.from. But I still want to talk about it for explanation. In the case above, call was used because we want to do something like:

let obj = { length: 2 }
obj.slice() //Uncaught TypeError: obj.slice is not a function

It would cause error because slice was defined in Array.prototype. Only Array instance can call that method. But actually in the implementation of slice, it doesn’t need to be called by Array instance and there is a lot of methods like this. So, in this case, call or apply would let non Array instance call these methods which means

Array.prototype.slice.call({ length: 2 })
//works like something like this
let obj = { length: 2 }
obj.slice = Array.prototype.slice
obj.slice()

And to help it easier to understand , you can remember it like:

method.call(thisArg, ...args)
//works like in most cases
thisArg.method = method
// or this way, if thisArg is a primitive value
Object.getPrototypeOf(thisArg).method = method
thisArg.method(...args)
//for apply
method.apply(thisArg, args)
//works like in most cases
thisArg.method = method
// or this way
Object.getPrototypeOf(thisArg).method = method
thisArg.method(...args)

Wasn’t that easy ?

So, let get back to Math.max.apply({}, [1, 2, 3, 4]). You can remember it like:

let thisArg = {}
thisArg.max = Math.max
thisArg.max(...[1, 2, 3, 4])

And more cases:

Object.prototype.toString.call([]) //"[object Array]"
//works like this
let thisArg = []
thisArg.toString = Object.prototype.toString
thisArg.toString() //"[object Array]"
//while
[].toString()//""

Or

;[' sd ', 1, 3].map(Function.prototype.call, String.prototype.trim) //['sd','1','3']
//works like
;[' sd ', 1, 3].map(function(...args) {
return String.prototype.trim.call(...args)
})
//works like
;[' sd ', 1, 3].map(function(...args) {
let thisArg = args[0]
thisArg.trim = String.prototype.trim
// way above wouldn't work because thisArg is a Primitive value, so we use way below instead.
Object.getPrototypeOf(thisArg).trim = String.prototype.trim
return thisArg.trim(...args.slice(1))
})

More in apply

As apply can accept an array-like object. So, what would happen if coding like:

Array.apply(null, { length: 2 })

Actually, it equals

Array.apply(null, [undefined, undefined])

So, you can understand it like:

let thisArg = {} //set null would get error in code below, also thisArg in above case is not important
thisArg.Array = Array
thisArg.Array(undefined, undefined)

Function.prototype.call.apply

You might have seen code using Function.prototype.call.apply which seems a little weird. However, it still make sense, especially in ES5. For example,

var arrayLike = { 0: 0, length: 1 }
Function.prototype.call.apply([].push, [arrayLike, 1])
console.log(arrayLike) //{0: 0, 1: 1, length: 2}

which works like

let arrayLike = { 0: 0, length: 1 }
let thisArg = [].push
thisArg.call(arrayLike, 1)
console.log(arrayLike) //{0: 0, 1: 1, length: 2}

also equal

let arrayLike = { 0: 0, length: 1 }
[].push.call(arrayLike,1)
console.log(arrayLike) //{0: 0, 1: 1, length: 2}

which works like

let arrayLike = { 0: 0, length: 1 }
let thisArg = arrayLike
thisArg.push = [].push
thisArg.push(1)
console.log(arrayLike) //{0: 0, 1: 1, length: 2}

Hope it's easier to understand `apply` and `call`.

[**Original Post**](https://github.com/xianshenglu/blog/issues/50)

Serval Ways to Force Update in Vue

Posted on 2018-12-01 | In vue

I have to mention this before we go on. As the doc-Forcing-an-Update says:

If you find yourself needing to force an update in Vue, in 99.99% of cases, you’ve made a mistake somewhere.

When I come back to write a blog, I find it’s totally true. Well, let’s begin. Here is the demo code based on element-ui@2.4.11 and vue@2.5.17:

<div id="app">
<p v-for="item in items" :key="item.id">{{ item.label }}</p>
<hr />
<el-tree
:data="items"
show-checkbox
node-key="id"
:default-expanded-keys="[2, 3]"
v-if="isElTreeShow"
:key="elTreeVersion"
>
</el-tree>
</div>
<script>
window.app = new Vue({
el: "#app",
data: {
isElTreeShow: true,
elTreeVersion: 100,
items: [
{
id: 1,
label: "Level one 1"
},
{
id: 2,
label: "Level one 2",
children: [
{
id: 21,
label: "Level two 2-1"
}
]
},
{
id: 3,
label: "Level one 3"
}
],
compare(a, b) {
return a.id - b.id;
},
compareReverse(a, b) {
return -this.compare(a, b);
}
}
});
</script>

Auto Update with Vue’s Reactivity System

Go check the doc.

$forceUpdate

For example, if someone made a mistake and wrote the code like

let length = app.items.length;
app.items[length] = { id: length + 1, label: `Level one ${length + 1}` };

You will not see the data update because you just add an nonreactive attribute. In this case, you might need app.$forceUpdate(). However, better idea is using code like:

let length = app.items.length;
app.items.push({ id: length + 1, label: `Level one ${length + 1}` });

or

let length = app.items.length;
this.$set(app.items, length, {
id: length + 1,
label: `Level one ${length + 1}`
});

Reassign

However, it’s common to use third party components. In this case, it may not be easy to modify the component if we find something not good. For example, if we sort the data using:

app.items.reverse();

Here is the result:

The part above the hr works as expected while the el-tree doesn’t change even you use $forceUpdate. So, in this case, what can we do?

We can make it update by reassigning like:

app.items = app.items.slice();

Until now, every thing about force update has been solved. I haven’t met problems which can’t be solved by ways above. However, there is some way stronger I have to mention.

v-if/key

In some cases, we do need to destroy and rebuild the component. But I didn’t find any API about rebuild except this issue. Some guys said we can rebuild using v-if="isElTreeShow":

app.isElTreeShow = !app.isElTreeShow;
app.$nextTick(() => {
app.isElTreeShow = !app.isElTreeShow;
});

or a better idea use :key="elTreeVersion"

app.elTreeVersion++;

See? That’s pretty cool.

Original Post

Remnant Shadows When Toggling HD Pictures with Alpha

Posted on 2018-12-01 | In js

See the demo:

<div id="app" class="app">
<img src="./images/hd3.png" class="app__image" id="app__image" />
<button class="app__button" id="app__button">next image</button>
</div>
<script>
let app__button = document.getElementById('app__button')
let app__image = document.getElementById('app__image')
app__button.addEventListener('click', function(event) {
app__image.style.visibility = 'hidden'
app__image.src = './images/hd4.png'
app__image.onload = function() {
app__image.style.visibility = 'visible'
}
})
</script>

The code is easy. But the images are special.

  • Type is png.
  • Size is more than 10M.
  • Alpha channel has been modified.
  • Both happen on my win7 and Mac 10.13.

In this case, when we click the button above, the result in Firefox and Safari would be:

If you look at it carefully, you would see the remnant shadows of previous image. That is unexpected because I change the src in the onload callback. Also, the same thing would happen in Chrome, though the frequency is much lower. So, how do we solve this?

Solution

let app__button = document.getElementById('app__button')
let app__image = document.getElementById('app__image')
app__button.addEventListener('click', function(event) {
app__image.src = '../images/transparent.png'
let tempImage = new Image()
tempImage.src = '../images/hd4.png'
tempImage.onload = function(event) {
// setTimeout(() => {
// if you are still worried, you can use setTimeout or requestAnimationFrame to delay
app__image.src = event.target.src
// }, 20)
}
})

See? We change the previous image with a transparent image. A little hack, but it works.

Obviously, there is a little interval between images onload and browsers’ ready to render the latest image, especially in Firefox and Safari. When the browsers’ performance becomes better this problem may not happen again. Anyway, hope we lucky.

Original Post

1…678…18

xianshenglu

54 posts
14 categories
142 tags
© 2023 xianshenglu
Powered by Hexo
|
Theme — NexT.Muse v5.1.4