我有一个添加到其中的Javascript文件。这是一个twitter插件,我添加了一个过滤器函数。
这是我的脚本(相关部分):
;(function ( $, window, document, undefined ) {
var pluginName = "twitterFeed",
defaults = {
username: null,
webservice_url: "/services/Scope/Country_United_States_Internet/TwitterService.svc/DoTwitterSearch",
num_tweets: 3
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
//if username is unknown
if(this.options.username == null) {
// do nothing
try{console.log('twitter username not found')}catch(err){};
return false;
}
// Get the tweets to display
this.getTweets();
$(".twitter-search input").on("change", function () {
var filters = this.formatFilters($(this).val());
this.getTweets(filters);
});
},
formatFilters : function(filterString) {
var hashtags = filterString.split(" ");
var hashtagString = "";
for (var i = 0; i < hashtags.length; i++) {
var hashtag = hashtags[i];
hashtag = hashtag.replace(",", "");
if (hashtag[0] !== "#") {
hashtag = "#" + hashtag;
}
hashtagString += " " + hashtag;
}
return hashtagString;
},
getTweets : function(filters){
var self = this;
var query = "from:" + self.options.username;
if (filters) {
query += filters;
}
var post_data = JSON.stringify(
{
"PageSize" : self.options.num_tweets,
"TwitterQuery" : query
}
);
$.ajax({
type: "POST", // Change to POST for development environment
url: this.options.webservice_url,
data: post_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout:2000,
success: function(data) {
// render the tweets
self.renderTweets(data.ContentItems);
},
error: function(error, type){
try{console.log(type);}catch(err){}
}
});
},我添加了$(".twitter-search input") on change事件(在init中),并添加了formatFilters()函数。然而,在onchange函数中,我得到了错误消息"this.formatFilters()没有定义“。我尝试删除this,但仍然收到"formatFilters() is not defined“的提示。
发布于 2016-07-12 00:56:45
请记住,事件处理程序中的this表示在其上激活事件的任何HTML元素。
相反,您需要跟踪实际的Plugin对象,而不是HTML元素。
var self = this;
$(".twitter-search input").on("change", function () {
var filters = self.formatFilters($(this).val());
self.getTweets(filters);
});发布于 2016-07-12 01:00:06
您遇到的问题与函数作用域有关。当在事件处理程序中引用它时,它指向回调作用域,而不是formatFilters函数的作用域。
要修复它-在init函数中,在第一行添加var self = this;,然后更改调用以使用self.formatFilters而不是this.formatFilters
https://stackoverflow.com/questions/38312261
复制相似问题