Although undocumented, the accept method is very useful in certain scenarios, for example when models have a load and save method. In such scenarios, you do not want an object to create a new object that replaces it in the parent viewModel.
Model.accept is especially good in this case because the result is dirty = false, which you want since the data is fresh from database. Unfortunately, this does not cope with MVVM because no change event is raised.
As a consequence, I have implemented a BaseModel to inherit from that overwrites the accept method as follows:
Is this a fix you would not recommend (any side effects)?
Is there an alternative use of the api that should be preferred?
Otherwise, is this something that could be fixed in Kendo UI?
var
Contact = kendo.data.Model.define({
id:
'id'
,
fields: {
...
},
load:
function
(id) {
var
that =
this
;
return $.ajax(...).done(
function
(data) {
that.accept(data);
});
},
save:
function
() {
return $.ajax(...);
}
});
Model.accept is especially good in this case because the result is dirty = false, which you want since the data is fresh from database. Unfortunately, this does not cope with MVVM because no change event is raised.
var
id=153, viewModel = kendo.observable({
contact =
new
Contact({});
});
contact.load(id); //does not raise a change event on the viewModel
As a consequence, I have implemented a BaseModel to inherit from that overwrites the accept method as follows:
var
BaseModel = Model.define({
accept:
function
(data) {
var
that =
this
;
//Call the base accept method
Model.fn.accept.call(that, data);
//Trigger a change event on the parent observable (possibly a viewModel)
if
($.type(that.parent) ===
'function'
) {
var
observable = that.parent();
if
(observable
instanceof
kendo.Observable) {
$.each(Object.keys(observable),
function
(index, key) {
if
(observable[key]
instanceof
that.constructor && observable[key].uid === that.uid) {
//we have found our nested object in the parent observable
observable.trigger(CHANGE, { field: key });
//otherwise UI won't be updated via MVVM
return
false
;
//once we have found the key and triggered the change event, break out of iteration
}
});
}
}
}
});
Is this a fix you would not recommend (any side effects)?
Is there an alternative use of the api that should be preferred?
Otherwise, is this something that could be fixed in Kendo UI?