🎯 Proxy Objects = Reactive Programming
State changes need reactions. JavaScript Proxy Objects ile reactive programming yapın.
🎯 Proxy Implementation
// 1. Basic Reactive Proxy
function createReactiveObject(target, onChange) {
return new Proxy(target, {
set(obj, prop, value) {
const oldValue = obj[prop];
obj[prop] = value;
onChange(prop, value, oldValue);
return true;
},
get(obj, prop) {
return obj[prop];
}
});
}
// 2. Usage
const state = createReactiveObject({ count: 0 }, (key, value, oldValue) => {
console.log(`${key} changed from ${oldValue} to ${value}`);
updateUI();
});
state.count = 5; // count changed from 0 to 5
// 3. Reactive Array
function createReactiveArray(array, onChange) {
return new Proxy(array, {
set(target, prop, value) {
target[prop] = value;
onChange(target);
return true;
},
get(target, prop) {
if (prop === 'push' || prop === 'pop' || prop === 'splice') {
return (...args) => {
const result = target[prop](...args);
onChange(target);
return result;
};
}
return target[prop];
}
});
}
// 4. Deep Reactive
function deepReactive(obj, onChange) {
return new Proxy(obj, {
set(target, prop, value) {
if (typeof value === 'object' && value !== null) {
value = deepReactive(value, onChange);
}
target[prop] = value;
onChange(target);
return true;
},
get(target, prop) {
const value = target[prop];
if (typeof value === 'object' && value !== null) {
return deepReactive(value, onChange);
}
return value;
}
});
}
✅ Proxy Kullanım Alanları
- ✓ State management
- ✓ Reactive UI frameworks
- ✓ Validation
- ✓ Lazy loading
- ✓ Virtual properties
Proxy objects, JavaScript’in en underrated özelliÄŸidir. Reactive programming’i native hale getirir.
