json-editor icon indicating copy to clipboard operation
json-editor copied to clipboard

editor.watch() and editor.on('change' -- receive no context

Open limor1 opened this issue 9 years ago • 3 comments

I was trying to get notification on arrays of booleans (checkboxes) and noticed that the called function was not receiving any context as to which instance of the array was changed. With editor.on('change', function().. there was no context received as parameter to the function or in "this". in the debugger, the call was "anonymous" so there was no context. With editor.watch() the problem is that it matches the path.to.field literally and not as a template path or regular expression so with an array, I would have to watch each possible array permutation:

Inputs.0.Graph.enable
Inputs.1.Graph.enable
..

I ended up using jquery to get a notification of changes with context $("input[name$='[Graph][enable]']").change(function(e) { which matches the DOM element <input type="checkbox" name="root[Inputs][0][Graph][enable]" style="width: auto; display: inline-block;"> But there is a simple change in core.js line 306 that could make watch() useful

  notifyWatchers: function(path) {
    if(!this.watchlist || !this.watchlist[path]) return this;
    for(var i=0; i<this.watchlist[path].length; i++) {
      this.watchlist[path][i]();
    }
  },

change !this.watchlist[path] with a loop that matches regex'ed watchlist strings (for example: path.test(this.watchlist[n]) would match against a regex such as Inputs.\d+.Graph.enable), and then call to the watchers passing the actual path parameter this.watchlist[n][i](path)

limor1 avatar May 11 '16 08:05 limor1

It would be really helpful if a context was passed to the callback to watch, without it I am unable to do things like know which item in a changed array is the one that triggered the callback.

jdp avatar Aug 13 '16 06:08 jdp

I encountered a need for the same mechanism today.

MgFrobozz avatar May 21 '18 23:05 MgFrobozz

https://github.com/jdorn/json-editor#deprecation-notice

https://github.com/json-editor/json-editor/issues/44

schmunk42 avatar May 22 '18 07:05 schmunk42