sapui5jsonmodeljavascript-databinding

Change event is not triggering for JSONModel


I have model called resources i need to listen to the change event i have attached the binding as below

var resModel = this.getModel("resources");
var resBinding = new Binding(resModel, "resources>/resources", resModel.getContext("/resources"));
resBinding.attachChange(this._resourceChanged.bind(this));

When I add the data to the model as below, change event is not triggered

var resources = this.getModel("resources").getProperty("/resources");
resources.push({
                 "res_num": 18,
                 "name": "New Added"
               });
this.getModel("resources").setProperty("/resources", resources);

But first time when i add the data to model it is triggering

this.resourceModel.setData({
  'resources': resources
});

Solution

  • By creating a Binding with a BindingContext like you do here

    new Binding(resModel, "resources>/resources", resModel.getContext("/resources"));
    

    in my understanding you actually create a binding to "resources>/resources//resources". When using a BindingContext the binding path should be relative (no leading "/"):

    new Binding(resModel, "resources>resources", resModel.getContext("/resources"));
    

    But most probably you don't even need a Context here so that this will be sufficient:

    new Binding(resModel, "resources>resources");
    

    Note that sap.ui.model.Binding is abstract and you might need to use sap.ui.model.PropertyBinding or sap.ui.model.ListBinding depending on the watched property being a plain property or an array.

    So why does your "change" still trigger initially? I guess that setData will just trigger ALL change listeners or your initial data fits the structure that you accidentally bound.

    I haven't tested the above. If you provide a JSBin that will be an easy thing to do.

    BR Chris