How to Implement Dom Data Binding in JavaScript

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 :

  1. Updated the data-bit to use lastName instead of LastName. Made it same as your state.
  2. Used getAttribute to get the value of the data-* 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 when
oProductDetailPanel.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:

  1. Element.prototype.bindElement equals to ManagedObject.prototype.bindObject

  2. oBinding.initialize() which means ClientContextBinding.prototype.initialize is called in ManagedObject.prototype._bindObject

  3. Binding.prototype._fireChange is called in the createBindingContext callback. Which fire change event: this.fireEvent("change", mArguments);

  4. 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;
  5. setElementBindingContext() calls ManagedObject.prototype.updateBindingContext eventually

  6. In updateBindingContext, the call stack is oBinding.setContext(oContext) -> JSONPropertyBinding.prototype.checkUpdate(because the sample use JSON Model here) -> this._fireChange({reason: ChangeReason.Change})

  7. For the second change event, the handler is in ManagedObject.prototype._bindProperty (There are many fModelChangeHandler in bind functions of ManagedObject, For our bindElement sample, we only need this one)

  8. 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



Leave a reply



Submit