John
January 7, 2022, 8:32am
1
Hi,
Original reference is not preserved in the object passed in props .
When my object was used in a component, I found the reference was not the original object.
The references of the whole object were changed recursively.
I believe the references being changed is done by this extend function,
} else if (isObject(to[nextKey]) && isObject(nextSource[nextKey])) {
extend(to[nextKey], nextSource[nextKey]);
} else if (!isObject(to[nextKey]) && isObject(nextSource[nextKey])) {
to[nextKey] = {};
extend(to[nextKey], nextSource[nextKey]);
} else {
to[nextKey] = nextSource[nextKey];
I thought I can pass my original object.
Is this behaviour by design?
.
.
.
.
demo:
window.testObj = { c: { d: { e: 3 } } };
routes: [
{
path: "/about",
componentUrl: "./pages/about.html",
options: {
props: {
testObj
}
}
}
]
// ==============
export default (props, context) => {
console.log({
"props.testObj": props.testObj,
"window.testObj": window.testObj,
"props.testObj == window.testObj": props.testObj == window.testObj,
"props.testObj.c == window.testObj.c": props.testObj.c == window.testObj.c
});
return $render;
};
output:
deejay
January 7, 2022, 11:12am
2
‘extend’ create a new object.
you should pass an array or class
window.obj = { key: 'value' };
window.arr = [{ key: 'value' }];
window.cls = new class { constructor(val) { this.key = val; } }('value');
const routes = [
{
path: '/path/',
componentUrl: '',
options: {
props: {
obj: window.obj,
arr: window.arr,
cls: window.cls
}
}
}
];
export default (props) => {
console.log(props.obj === window.obj); //false
console.log(props.arr === window.arr); //true
console.log(props.cls === window.cls); //true
};
John
January 10, 2022, 3:02am
3
OK, this is a workaround.
The array method is ok.
I know there is utils.merge() inside Framework7 and it doesn’t replace the references.
I am just doubting why extend() is used here and not merge().
deejay
January 10, 2022, 7:33am
4
they are not the same
// import utils
let obj1 = { obj: { key: 'value' } };
let obj2 = { obj: {} };
let merge = utils.merge({},obj1,obj2);
console.log(merge); // { obj: {} }
let obj3 = { obj: { key: 'value' } };
let obj4 = { obj: {} };
let extend1 = utils.extend({},obj3,obj4);
console.log(extend1); // { obj: { key: 'value' } }
let obj5 = { obj: { key: 'value' } };
let obj6 = { obj: {} };
let extend2 = utils.extend(true,{},obj5,obj6);
console.log(extend2); // { obj: { key: 'value' } }
let obj7 = { obj: { key: 'value' } };
let obj8 = { obj: {} };
let extend3 = utils.extend(false,{},obj7,obj8);
console.log(extend3); // { obj: {} }
This is by design to keep the data you pass to Framework7 params, routes, etc. - immutable, otherwise it can produce unwanted side effects
1 Like
John
January 10, 2022, 4:06pm
6
I see. thanks!
(Post must be at least 20 chars)