Javascript Dynamic Data binding code not working
I made some changes to the fiddle to get the desired result. The problem was with your logic to refer the elements using the dataset
attributes, so I tried to simplify it.
Some notable changes :
- Updated the
data-bit
to uselastName
instead ofLastName
. Made it same as your state. - Used
getAttribute
to get the value of thedata-*
properties to correctly get the reference.
I think this is what you're looking for:
const createState = (stateObj) => {
return new Proxy(stateObj, {
set(target, property, value) {
target[property] = value;
render();
return true;
}
});
};
const state = createState({
name: '',
lastName: ''
});
const listeners = document.querySelectorAll('[bit-data]');
listeners.forEach((element) => {
const name = element.getAttribute('bit-data');
console.log('here', element.getAttribute('bit-data'), JSON.stringify(element.dataset))
element.addEventListener('keyup', (event) => {
state[name] = element.value;
console.log(state);
});
});
const render = () => {
const bindings = Array.from(document.querySelectorAll('[bit-data-binding]')).map((e) => {
return e.getAttribute('bit-data-binding');
});
//console.log('bindings:', bindings, document.querySelectorAll('[bit-data-binding]'));
(bindings ?? []).forEach((binding) => {
document.querySelector(`[bit-data-binding=${binding}]`).innerHTML = state[binding];
document.querySelector(`[bit-data=${binding}]`).value = state[binding];
});
}
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Frontend Framework</title>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" bit-data="name"/>
<span bit-data-binding="name" style="margin-left: 1rem;"></span>
</div>
<div>
<label>Lastname:</label>
<input type="text" bit-data="lastName"/>
<span bit-data-binding="lastName" style="margin-left: 1rem;"></span>
</div>
</body>
</html>
how to use data binding for getting a value from user input and multiplay with contents with {{ ...}}
Here is the solution please follow the below link.
https://stackblitz.com/edit/angular-ivy-w6dvcq?file=src%2Fapp%2Fapp.component.ts
Data binding to a dynamic path in Polymer
Polymer data bindings don't support nesting or expressions. You would likely have to use a computed binding like this:
// template's computed binding
[[_getChoice(question, user.uid)]]
// script
Polymer({
_getChoice: function(question, uid) {
return question.answers[uid].choice;
},
...
});
How is data binding implemented in SAPUI5?
Some comments said UI5 use Handlebars for data binding, and after search, Handlebars only support for one-time data binding. What I am more curious is how two-way data binding implemented in UI5(Sorry for not making this clear in the first place).
In Handlebars,once you compiled your template, the view/DOM has nothing to do with the data model.
But two-way data binding connects data to a property or attribute of an element in its local DOM. Which means:
When properties in the model get updated, so does the UI. When UI elements get updated, the changes get propagated back to the model.
https://stackoverflow.com/a/13504965/5238583
In the question of How to Implement DOM Data Binding in JavaScript
, many techniques are mentioned. UI5 uses these two(what I've found so far): add change event listener and mutators(setter)
I used this official sample for example: Data Binding - Step 13 - Element Binding
data binding changes whenoProductDetailPanel.bindElement({ path: sPath, model: "products" });
is called.
Set break points in oBinding.setContext() in ManagedObject.prototype.updateBindingContext and ManagedObject.prototype.updateProperty. And you can see it in call stack.
TL;DR: Core steps are 3, 6, 8
The main steps are:
Element.prototype.bindElement
equals to ManagedObject.prototype.bindObjectoBinding.initialize() which means ClientContextBinding.prototype.initialize is called in
ManagedObject.prototype._bindObject
Binding.prototype._fireChange is called in the
createBindingContext
callback. Which firechange
event:this.fireEvent("change", mArguments)
;And! The change event handler is defined in
ManagedObject.prototype._bindObject
:var fChangeHandler = function(oEvent) {
that.setElementBindingContext(oBinding.getBoundContext(), sModelName);
};
oBinding.attachChange(fChangeHandler);
oBindingInfo.modelChangeHandler = fChangeHandler;setElementBindingContext()
callsManagedObject.prototype.updateBindingContext
eventuallyIn
updateBindingContext
, the call stack isoBinding.setContext(oContext)
->JSONPropertyBinding.prototype.checkUpdate
(because the sample use JSON Model here) ->this._fireChange({reason: ChangeReason.Change})
For the second change event, the handler is in ManagedObject.prototype._bindProperty (There are many
fModelChangeHandler
in bind functions of ManagedObject, For ourbindElement
sample, we only need this one)In the
fModelChangeHandler
,ManagedObject.prototype.updateProperty
is called. That where our setter(mutator) is used:
whenever a property binding is changed.This method gets the external format from the property binding and applies it to the setter.
this[oPropertyInfo._sMutator](oValue);
. For our sample oPropertyInfo._sMutator
is setValue
. execute this, the value in Input <Input value="{products>ProductID}"/>
will be changed.
Original record here: https://github.com/TinaC/Blog/blob/master/SAPUI5/Data_Binding.md
Related Topics
What Does This Symbol Mean in JavaScript
Is There a Regexp.Escape Function in JavaScript
What Is JavaScript'S Highest Integer Value That a Number Can Go to Without Losing Precision
How to Determine Equality For Two JavaScript Objects
Get Selected Value in Dropdown List Using JavaScript
Get the Values from the "Get" Parameters (JavaScript)
Object Comparison in JavaScript
Open a Url in a New Tab (And Not a New Window)
How to Access Previous Promise Results in a .Then() Chain
Disable Same Origin Policy in Chrome
How to Print a Number With Commas as Thousands Separators in JavaScript
Understanding the Difference Between Object.Create() and New Somefunction()
Run JavaScript Function When User Finishes Typing Instead of on Key Up