您需要在回调中处理您的逻辑。你应该怎么做取决于你的代码。
如果你把console.dir(data)
而不是return data;
你应该看到你的回应。
所以你应该把应该对数据做一些事情的相应代码放在那里。或者我们jQuery.proxy
或者Function.prototype.bind
将你的回调绑定到一个对象。但无论您如何创建传递给 的回调getJson
,它都必须是您使用数据的执行路径的来源。
为了说明异步行为,请检查您的代码的此修改:
var JsonHandler = function(){
return{
json : function(url){
return $.getJSON(url, function(data){
console.log("data received");
console.dir(data);
});
}
}
};
(function ($) {
var path = "js/data.json";
var getJson = new JsonHandler();
console.log("before json request");
getJson.json(path);// i am getting a object instead of json response..
console.log("after json request");
})(jQuery);
编辑
这是一个发布/订阅系统的示例(代码目前更多是伪代码 - 尚未对其进行语法错误测试,但我会在几个小时内修复可能存在的错误)
var JsonHandler = {
request : function( url, params, key ) {
$.getJSON(url, params, function(data){
//because of js scopes the 'key' is the one that is used for requesting the data
JsonHandler._publishData(data, key);
});
},
_subcribers : {},
/*
key could also be path like this:
/news/topic1
/news/topic2
/news
so code subscribes for '/new' it will be notifed for /news/topic1, /news/topic2, /news
*/
subscribe : function( key, callback ) {
/*
The path logic is missing here but should not be that problematic to added if you understood the idea
*/
this._subcribers[key] = this._subcribers[key]||[];
this._subcribers[key].push(callback);
},
_publishData : function( data, key ) {
/*
check if there are subscribers for that key and if yes call notify them
This part is also missing the path logic mention above, is just checks for the key
*/
if ( this._subcribers[key] ) {
var subscribers = this._subcribers[key];
for( var i = 0, count = subscribers.length ; i<count ; i++ ) {
subscribers[i](data,key);
}
}
}
}
var AnObject = function() {
}
AnObject.prototype = {
updateNews : function(data, key) {
console.log("received data for key: "+ key);
console.dir(data);
}
};
var obj = new AnObject();
//add a simple callback
JsonHandler.subscribe( "/news", function(data, key ) ) {
console.log("received data for key: "+ key);
console.dir(data);
});
//add a callback to a 'method' of an object
JsonHandler.subscribe( "/news", obj.updateNews.bind(obj) );
JsonHandler.request("some/url",{/* the parameters */}, "/news");