Hi all,
I want to introduce a (pseudocode) concept of extending Data API with ability to track data changes, similar to Rails DirtyAttributes
and/or Backbone.Model
. Current API introduces only get, set, has, delete
functions.
One could extend current Data
class with methods:
/**
* Returns changes of value of given attribute.
* @param name - name of attribute whose value changed
* @return Array<string> - 2 element array containing value before change and current value
*/
changes(name: string) : Array<string>
/**
* Returns names of all attributes which were changed.
* @return Array<string> - array of names of attributes where value changed
*/
changed() : Array<string>
/**
* Removes information about attribute changes.
*/
clean() : void
/**
* Listens for changes of value of given attribute.
* @param name - name of attribute to listen for value changes
* @param function - callback function with value changes: fn(before: string, after: string)
* @return Array<string> - array containing value before change and current value
*/
onChange(name: string, function(before: string, after: string))
and introduce a new DirtyData
Object like so:
class DirtyData {
key: string,
value: Array<string>
}
as a Hash
of attribute name as key
and value changes as value
.
Here is the sample usage:
Data Object: "foo"
DirtyData Object: { "foo": ["bar", "baz"] }
data.onChange("foo", (before, after) => {
console.log("foo changed", before, after)
})
data.get("foo") -> "bar"
data.set("foo", "baz")
// log: "foo changed", "bar", "baz"
data.get("foo") -> "baz"
data.changed() -> ["foo"]
data.changes("foo") -> ["bar", "baz"]
data.clean()
data.changed() -> []
What do You think of such approach? Such PR can be pulled to core?
I think that it could be implemented using MutationObserver
and/or MutationRecord
.
Above approach would only apply to state of data in controller’s element.