Am trying to advance my javascript code, by using it as an object so i can call it when needed but it doesn't work. Please can someone help me out i will appreciate it.
var AppObject = {
var targetElement = "#AjaxLoadBodyContentLoader";
init: function (hashUrl, defaultBack){
if(hashUrl != defaultBack && hashUrl != ""){
var LoadHashUrl = hashUrl+' #AjaxLoadBodyContentLoader';
$('#AjaxLoadBodyContentLoader').load(
LoadHashUrl,
{"async_content" : "true", "PrevLink" : defaultBack}
);
}
},
asyncShowContent: function(){
/*$.getScript("external.js");*/
$(this.targetElement).show('normal', this.asyncPregressBar);
},
asyncPregressBar: function(){
$('#preloader').fadeOut();
$('#status').fadeOut();
},
asyncLoader: function(){
$(this.targetElement).load(
this.linkPath,
{"async_content" : "true", "PrevLink" : this.PrevLink},
function(responseTxt, statusTxt, xhr){
this.asyncShowContent();
console.log("Status: " + xhr.status + " | Text: " + xhr.statusText);
}
);
},
asyncExtecute: function(e){
var targetUrl = e.target.href;
if(typeof targetUrl == 'undefined' || targetUrl == ""){
targetUrl = $(this).attr('href');
}
var linkPath = targetUrl + ' ' + this.targetElement;
var PrevLink = $(this).attr('data-page-link');
window.location.hash = targetUrl;
$('#preloader').fadeIn();
$('#status').fadeIn();
$(this.targetElement).hide('fast',this.asyncLoader);
}
}
Using the above code without adding it inside AppObject={}
, work very fine, but i want to advance it and learn more how to use javascript object.
Usage
$(function(){
AppObject.init(
window.location.hash.substr(1),
location.href.replace(location.hash,"")
);
$(document).on('click', 'a.LoadPage', function(e){
AppObject.asyncExtecute(e);
});
});
As @musefan says in a comment, you have a syntax problem:
This is wrong:
var AppObject = {
var targetElement = "#AjaxLoadBodyContentLoader";
...
}
This is a variable declaration:
var targetElement = "#AjaxLoadBodyContentLoader";
Inside an object, you need to use key/value pairs :
var AppObject = {
targetElement : "#AjaxLoadBodyContentLoader",
...
}
EDIT : e is undefined
e
should be your event, you need it in asyncExtecute,
var AppObject = {
asyncExtecute: function(e){
e.preventDefault(); // Add this line, to prevent the browser to immediately navigate to other window
var targetUrl = e.target.href;
...
}
}
$(function(){
...
$(document).on('click', 'a.LoadPage', function(e){
AppObject.asyncExtecute(e); // Here you are passing the event object to asyncExtecute
});
});
Problem is the way you are adding property to your object. Please add it as below:
var AppObject = {
targetElement: "#AjaxLoadBodyContentLoader",
//remaining code---
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.