我对Jquery中的匿名函数感到困惑
在一个教程中,我看到他们使用JSON从twitter获取信息,然后粘贴到模板(把手)中。我对JSON和从服务器获取信息的概念非常陌生,但最让我困惑的是,$.JSON和$map中的匿名函数使用回调函数并传递一些参数。我不明白他们从哪里来,为什么要引用他们。如果有人能给我一个线索,那就太好了。 谢谢我对Jquery中的匿名函数感到困惑,jquery,json,function,Jquery,Json,Function,在一个教程中,我看到他们使用JSON从twitter获取信息,然后粘贴到模板(把手)中。我对JSON和从服务器获取信息的概念非常陌生,但最让我困惑的是,$.JSON和$map中的匿名函数使用回调函数并传递一些参数。我不明白他们从哪里来,为什么要引用他们。如果有人能给我一个线索,那就太好了。 谢谢 Twiiter API {{{#每个这个} {{/每个}} (功能(){ 变量Twitter={ 初始化:函数(配置){ this.url=http://search.twitter.com
Twiiter API
{{{#每个这个}
-
{{/每个}}
(功能(){
变量Twitter={
初始化:函数(配置){
this.url=http://search.twitter.com/search.json?q=“+config.query+”&回调=?”;
this.template=config.template;
this.container=config.container;
this.fetch();
},
attachTemplate:函数(){
var template=handlebar.compile(this.template);
append(模板(this.tweets));
},
fetch:function(){
var self=this;//这是指TWITTER对象
$.getJSON(this.url,函数(数据){
//$.map将通过一个数组进行过滤,并为每个数组执行一个函数
self.tweets=$.map(data.results,function)(tweet){
返回{
作者:tweet.from_用户,
tweet:tweet.text,
拇指:tweet.profile\u image\u url,
网址:'http://twitter.com/“+tweet.form_user+”/status/'+tweet.id_str
};
});
self.attachTemplate();
});
}
};
Twitter.init({
模板:$(“#推文模板”).html(),
容器:$('ul.tweets'),
查询:“tutspremium”
});
})();
在提出这些问题之前,您必须进行一次良好的搜索
有关匿名函数的详细信息,请参见:
关于模板制作,请点击这里
关于回调函数的一些见解
你不明白什么?我对$.Json中的数据和$map中的推文感到困惑,我不知道它们从哪里来,为什么需要它
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Twiiter API</title>
</head>
<body>
<ul class="tweets">
<script id="tweets-template" type="text/x-handlebars-template" >
{{#each this}}
<li>
<img src = "{{thumb}}" alt= "{{author}}">
<p><a href="{{url}}">{{tweet}}</a></p>
</li>
{{/each}}
</script>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>
<script>
(function(){
var Twitter = {
init: function(config){
this.url = 'http://search.twitter.com/search.json?q=' + config.query + '&callback=?';
this.template = config.template;
this.container = config.container;
this.fetch();
},
attachTemplate : function(){
var template = Handlebars.compile(this.template);
this.container.append(template (this.tweets));
},
fetch: function(){
var self = this; // This REFERS TO TWITTER OBJECT
$.getJSON(this.url, function (data){
//$.map WILL FILTER THROUGH AN ARRAY AND FOR EACH ONE OF THOES IT WILL EXECUTE A FUNCTION
self.tweets = $.map(data.results, function(tweet){
return {
author : tweet.from_user,
tweet : tweet.text,
thumb: tweet.profile_image_url,
url: 'http://twitter.com/' + tweet.form_user + '/status/' + tweet.id_str
};
});
self.attachTemplate();
});
}
};
Twitter.init({
template:$('#tweets-template').html(),
container:$('ul.tweets'),
query: 'tutspremium'
});
})();
</script>
</body>
</html>