So I am writing something using augment for inheritance and for some reason I can run this.setButtons(type) and console.log(this.buttons) in that method, but when I run my this.getButtons() it comes back as undefined, even though getButtons just returns this.buttons. Any help would be greately appreciated. I will post up all the code I have so far, because maybe I'm not inheriting properly. Thank you in advance.
var ContextMixin = function () {};
ContextMixin.prototype = {
createElements: function (el, mode, type) {
var m;
if (mode == 'exact') {
$("#" + el).append("<ul id='contextmenu'>");
} else {
$(el).each(function () {
m = $(this).append("<ul id='contextmenu'>");
});
$('body').append(m);
}
$("#contextmenu").css({
'position': 'absolute',
top: 13,
left: 13
});
var new_buttons = this.getButtons();
$.each(this.buttons['buttons'], function () {
m.append("<li id='" + this + "'>" + this + "</li>");
});
},
attachEvents: function () {
functions = this.getFunctions(type);
buttons = this.getButtons();
for (index in buttons['buttons']) {
addEvent(buttons['buttons'][index], this.functions[index][0], this.functions[index][1]);
};
},
setFunctions: function (type) {
var callback = {
success: function (msg) {
this.functions = msg;
},
failure: function () {
alert('Error getting functions')
}
};
$.ajax({
type: 'GET',
url: 'function_list.php?type=' + type,
success: function (msg) {
this.functions = msg;
}
});
},
getFunctions: function () {
return this.functions;
},
setType: function (value) {
this.type = value;
},
getType: function () {
return this.type;
},
setButtons: function (type) {
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function (reply) {
this.buttons = reply;
}
});
},
getButtons: function () {
return this.buttons;
}
}
function createMenu(el, type, mode) {
this.setButtons(type);
this.setFunctions(type);
this.createElements(el, mode, type);
}
augment(createMenu, ContextMixin);
function augment(receivingClass, givingClass) {
if (arguments[2]) { //Only give certain methods.
for (var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
} else { //Give all methods
for (methodName in givingClass.prototype) {
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
Because this in the callback to the AJAX request is not your object.
Here's a common fix...
setButtons: function(type) {
var self = this; // keep a reference to this
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
self.buttons = reply; // use the reference here
}
});
},
...but a better fix is to use the context: property of the $.ajax request...
setButtons: function(type) {
$.ajax({
type: 'GET',
context: this, // set the context of the callback functions
url: 'button_list.php?type=' + type,
success: function(reply) {
this.buttons = reply;
}
});
},
If you change
ContextMixin.prototype = {
createElements
to
ContextMixin.prototype.createElements
it should work.
this is not what you think it is in your ajax callback—instead of being your current object, it's actually the global object the XHR object. All your callback is doing is putting a buttons property onto the xhr object.
You need to save this before your function runs:
setButtons: function(type) {
var self = this;
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
alert(reply);
self.buttons = reply;
}
});
},
Related
I was trying to call the callback function with classname, defined in another javascript file, but I was failed to call. I didn't get the mistake I did. Please let me know the mistake I did in below code and Thank you show much for your help.
I have created one central javascript file like below
CentralScript.js
function CentralScript() {
}
CentralScript.prototype.makeRequest = function (className, cbf, dataToSend) {
$.ajax({
url: 'apiurl',
type: 'POST',
dataType: 'json',
data: {
parameters : dataToSend
},
success: function (responseData) {
this.showResponse(className, cbf, responseData);
},
complete: function() {
},
error: function () {
console.log("Error occurred...");
}
});
};
CentralScript.prototype.showResponse = function (className, cbf, data) {
className.cbf(data);
};
and I have created another file like below
SomeFile.js
function SomeFile() {
}
SomeFile.prototype.sayHi = function() {
var obj = new CentralScript();
var dataToSend = {
method: 'someMethod'
};
obj.makeRequest('SomeFile', 'resultToShow', dataToSend);
};
SomeFile.resultToShow = function (data) {
console.log(data);
};
and I have created main.js file like below
main.js
var ProjectName= (function() {
var sfObj;
function init() {
createObjects();
initiateProject();
}
function createObjects() {
sfObj = new SomeFile();
}
function initiateProject() {
sfObj.sayHi();
}
return {
init : init
};
})();
$(ProjectName.init);
I was getting the response when I was making ajax request from SomeFile.js file, but the response was not logging in console.
I am getting 'cbf' as undefined in 'showResponse' function present in CentralScript.js file
CentralScript.prototype.showResponse = function (className, cbf, data) {
className.cbf(data);
};
May I call the callback function like this "className.cbf(data);" present in SomeFile.js
Please let me know the mistake I did and Thank you show much for your help.
The problem has nothing to several files.
This is corrected script:
//CentralScript.js
function CentralScript() {
}
CentralScript.prototype.makeRequest = function (className, cbf, dataToSend) {
var $this = this;//save for further use
$.ajax({
url: 'apiurl',
type: 'POST',
dataType: 'json',
data: {
parameters: dataToSend
},
success: function (responseData) {
//cbf(responseData);//cbf is SomeFile.resultToShow
$this.showResponse(className, cbf, responseData);//this is $.ajax here
},
complete: function () {
},
error: function () {
console.log("Error occurred...");
}
});
};
CentralScript.prototype.showResponse = function (className, cbf, data) {
//className.cbf(data);//undefined
cbf(data);//cbf is SomeFile.resultToShow
};
//SomeFile.js
function SomeFile() {
}
SomeFile.prototype.sayHi = function () {
var obj = new CentralScript();
var dataToSend = {
method: 'someMethod'
};
//obj.makeRequest('SomeFile', 'resultToShow', dataToSend);
obj.makeRequest(this, this.resultToShow, dataToSend);//this is SomeFile
};
SomeFile.prototype.resultToShow = function (data) {//need .prototype to add function to SomeFile
console.log(JSON.stringify(data));
};
I have two javascript function which populate some data using jquery json. Both working fine but problem is that second function getting called before first one execute. My code is :
$(document).ready(function () {
loadSubject();
getTopic();
});
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
alert('22222');
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
function getTopic() {
var c = $('#cCount').val();
alert(c);
for (var i = 1; i <= c; i++) {
var subId = $('#hdn_' + i).val();
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Topic', UserRecId: 0, ParentId: subId },
dataType: 'json',
success: function (data) {
var topicDivs = "";
var divs = "";
tDivs = '';
$.each(data, function (index, value) {
divs = '';
divs = '<div class="row">';
divs = divs + '<div class="subject">' + value.Name + '</div>';
divs = divs + "</div>";
topicDivs = topicDivs + divs;
});
$('#sDiv_' + i).html(topicDivs);
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
}
This is not the way how ajax get executes. If you put two jquery ajax requests one by one then they will execute in sequence by it is not necessary that second request will be executed after first request completes or response of first request is received.
If you want this to happen then there are two ways
1. Use async:'false'
This makes a request to wait until response is recieved before executing next statement in javascript.
What does "async: false" do in jQuery.ajax()?
2. Use callbacks
Write the second function which you want to execute in success or complete callback of your first ajax request.
jQuery ajax success callback function definition
Try adding return statement before $.ajax({}) within both loadSubject and getTopic , to return jQuery promise object , which can be handled at deferred.then
function loadSubject() {
return $.ajax()
}
function getTopic() {
return $.ajax()
}
loadSubject().then(getTopic);
function a() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(1)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
function b() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(2)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
a().then(b)
You have to add async:false in your first ajax request, it stop next execution till first ajax request will complete its execution.
So your first function like this
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
async:false,
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Call second function from first ajax success function
$(document).ready(function () {
loadSubject();
});
function loadSubject() {
// code here
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
//code here
getTopic(); // Second function calling
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Now when first function is executed successfully then second function will be called.
I am using following code to fetch and cache data from a ASP.NET handler. The problem is that whenever I cache data using a button click its working fine, but I want this to happen at document.ready() event. When I executed this code on document.ready() event, its fetching data perfectly, but its not getting data from the cache when I reload the page.
var localCache = {
data: {},
remove: function (url) {
delete localCache.data[url];
},
exist: function (url) {
return localCache.data.hasOwnProperty(url) && localCache.data[url] !== null;
},
get: function (url) {
console.log('Getting in cache for url' + url);
return localCache.data[url];
},
set: function (url, cachedData, callback) {
cacheTime = (new Date()).getTime();
localCache.remove(url);
localCache.data[url] = cachedData;
if ($.isFunction(callback)) callback(cachedData);
}
};
var now;
var cacheTime;
var tDiff;
function getValueAtIndex(index) {
var str = window.location.href;
return str.split("/")[index];
}
//$(document).ready(function () {
$('#Button1').click(function (e) {
var url = '/Handlers/ResponseFetcher.ashx';
var topicid = "<%=desid %>";
$.ajax({
url: url,
type: "POST",
data:
JSON.stringify({ tid: topicid })
,
dataType: "json",
cache: true,
beforeSend: function () {
now = (new Date()).getTime();
if (localCache.exist(url)) {
tDiff = now - cacheTime;
if (tDiff < 20000) {
loadData(localCache.get(url));
return false;
}
}
return true;
},
complete: function (jqXHR, textStatus) {
localCache.set(url, jqXHR, loadData);
}
});
});
function loadData(data) {
console.log("now: " + now + ", cacheTime: " + cacheTime + ", tDiff:" + (cacheTime - now));
$('#responseloader').hide();
var resdata = JSON.parse(data.responseText);
$(resdata).each(function (i) {
$('#responsecontainer').append("<div>" + this.Title + "</div>");
});
}
Here tDiff will be undefined on first run. Is this the problem? or caching doesn't work if the page is reloaded? Please help!
I have been using knockout.js for a while now, and haven't encountered this problem before. Usually, when I try to push a new js object to an observableArray, it works without an issue, but for some reason, this time around I'm getting this error:
TypeError: self.Students.push is not a function
Here is a snippet of my code:
window.ApiClient = {
ServiceUrl: "/api/students",
Start: function () {
var viewModel = ApiClient.ViewModel(ngon.ClientViewModel);
ko.applyBindings(viewModel);
viewModel.get();
}
};
ApiClient.ViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
this.get = function (id) {
if (id == undefined) {
return ApiClient.Service.get(self.PageSize(), self.PageNumber(), function (data) {
self.Students(data);
});
}
}
this.post = function () {
return ApiClient.Service.post(self.DetailedStudent, function (data) {
self.Students.push(data);
});
}
return this;
}
ApiClient.Service = function () {
var _get = function (pageSize, pageNumber, callback) {
sv.shouldShowLoading = false;
var queryParams = String.format("?pageSize={0}&pageNumber={1}", pageSize, pageNumber);
$.ajax(ApiClient.ServiceUrl + queryParams, {
dataType: "json",
type: "get",
success: callback
});
}
var _post = function (student, callback) {
$.ajax(ApiClient.ServiceUrl, {
data: ko.mapping.toJSON(student),
type: "post",
contentType: "application/json; charset-utf-8",
statusCode: {
201 /*Created*/: callback,
400 /*BadRequest*/: function (jqxhr) {
var validationResult = $.parseJSON(jqxhr.responseText);
alert(jqxhr.responseText);
}
}
});
}
return {
get: _get,
post: _post
};
}();
$(document).ready(function () {
ApiClient.Start();
});
My student object is a very simple C# object that has Id, FirstName, LastName. The get() function works without any issues, it's just the callback function from the post() that cannot push the resulting data. Also, the data being returned back from the server looks correct:
{"Id":"rea","FirstName":"asdf","MiddleName":null,"LastName":"rrr"}
I solved this! It's because the initial viewModel, when being instantiated by the page's view model object had 'null' for its Students property.
knockout.js requires non-null values for all fields that are to be auto mapped.
i have a problem. I am trying to add a functions return value to a variable but it says the function is undefined. Here is my code. :
var selectedExpenseList = getSelectedExpenseIDs();
here is my function:
function getSelectedExpenseIDs() {
var selectedExpensesList = new Array;
var i = 0;
$('.expenseCheckBox:checked').each(function () {
if ($(this)[0].id !== "checkAllExpenses") {
selectedExpensesList[i] = $(this)[0].id.split('_')[1];
++i;
}
});
return selectedExpensesList;
}
EDIT: here is my entire function: I am trying to delete something from a list if a person has checked it.
var selectedExpenseList;
function actuallyDeleteTheExpense(canDeleteExpenses)
{
selectedTasksList = getSelectedTaskIDs();
var deleteTrackers = false, deleteExpenses = false;
if (canDeleteExpenses && !canDeleteTrackers)
{
$.Zebra_Dialog('Do you wish to remove Expenses?',
{
'type': 'question',
'title': 'Confirmation',
'buttons': [
{
caption: 'Yes', callback: function () {
deleteTrackers = false;
deleteExpenses = true;
doTheDelete(deleteExpenses);
}
},
{
caption: 'No',
callback: function () {
doTheDelete(deleteExpenses);
}
}
]
});
}
}
function doTheDelete(doIDeleteExpenses)
{
if (selectedTasksList.length > 0)
{
$.ajax({
type: "POST",
//url: "/Tasks/ViewTasks.aspx/deleteTasksAndLinkedItems",
url: '<%=ResolveUrl("~/Expenses/ViewExpenses.aspx/deleteSelectedExpense")%>',
data: "{ 'TaskIDs': [" + selectedTasksList.join(',') + "], DeleteTrackers : " + doIDeleteTrackers + ", DeleteExpenses : " + doIDeleteExpenses + " }",
//fix data
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var ss = data.d;
if (ss.length > 0) {
for (var i = 0; i < ss.length; ++i) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true });
alert(ss[i]);
}
}
$("#viewTasksGrid").flexReload();
},
error: function (data) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true, modal: true });
alert('Error Deleting Tasks');
if (window.console) {
console.log(data);
}
}
});
} else {
showMessage('No tasks are selected.');
}
}
//end delete expense
function getSelectedExpenseIDs() {
var selectedExpensesList = new Array;
var i = 0;
$('.expenseCheckBox:checked').each(function () {
if ($(this)[0].id !== "checkAllExpenses") {
selectedExpensesList[i] = $(this)[0].id.split('_')[1];
++i;
}
});
return selectedExpensesList;
}
I noticed that your function code is tabbed once more than your code that calls it. It's possible that your function is scoped improperly (e.g. it's declared inside another function and you're calling it from outside that function).
If your function is coming back as undefined, it's almost certainly a scoping issue. I see nothing wrong with the function itself.
For instance:
$(document).ready(function () {
function myFunction() {
return 3;
}
});
var bob = myFunction(); //Error: myFunction is not defined.