I am testing the SAPUI5 framework with a little todo list application. I have a database and access the data through a REST Service. I am able to get everything into my UI and from the UI into the database.
However, i am saving a reference of the database data in an JSON model which is mapped to a Table i am showing on the UI. When i try to add/delete elements, the writing to the database seem to work correctly but my intern model variable loses its reference between the different function calls ("initToDoModel" and "addToDo" for example). Here is the code:
sap.ui.controller("sapui5_test.SAPUI5_Test", {
//THIS IS THE REFFERENCE
todoModel : null,
addTodo : function(text) {
this.doAjax("/add", {
text : text
}).done(function(todo) {
//HERE todoModel IS UNDEFINED BUT WAS SET IN initTodoModel
this.todoModel.getProperty("/").push(todo);
this.todoModel.updateBindings();
this.getView().rerender();
});
},
initTodoModel : function() {
var oModel = new sap.ui.model.json.JSONModel();
var aData = jQuery.ajax({
type : "GET",
contentType : "application/json",
url : "http://sapm04.ibsolution.local:50000/demo.sap.com~d337_resttest_web/rest/todo/init/",
dataType : "json",
async: false,
success : function(data,textStatus, jqXHR) {
oModel.setData({modelData : data});
//HERE THE todoModel IS SET
this.todoModel = oModel;
alert("Ok");
}
});
return oModel;
},
doAjax : function(path, content, type, async) {
var params = {
url : "http://sapm04.ibsolution.local:50000/demo.sap.com~d337_resttest_web/rest/todo" + path,
dataType : "json",
contentType : "application/json",
context : this,
//async : false,
cache : false
};
params["type"] = type || "POST";
if (async === false) {
params["async"] = async;
}
if (content) {
params["data"] = JSON.stringify(content);
}
return jQuery.ajax(params);
},
getTodo : function(id) {
var index, todo;
jQuery.each(this.todoModel.getProperty("/"), function(i, t) {
if (t.id === id) {
index = i;
todo = t;
}
});
return {
index : index,
todo : todo
};
}
});
so the initToDoModel function is called every time the page is loaded, gets data from db, maps it into an JSONModel object. Then when i click the Add Button on my page the addToDo function is called and needs to update the cached JSONModel which is undefined by this time.
I am new to JavaScript so maybe someone could explain what is happening there.