我想从动态创建的函数中调用当前实例原型函数,但我无法实现。我使用Google Firebase Friendly Chat example。
这是JS文件。
// Initializes FriendlyChat.
var chat = "test";
function FriendlyChat() {
this.checkSetup();
$("#l_chat").html("");
this.initFirebase();
//LOAD ALL CHATs
this.database1 = firebase.database();
this.messagesRef1 = this.database1.ref('messages/');
this.messagesRef1.on("child_added", function(snapshot, prevChildKey) {
var newPost = snapshot.val();
console.log(newPost);
var name1 = String(snapshot.key);
document.getElementById("l_chat").innerHTML += '<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-color-text--white" onclick="click1(\'' + name1 + '\');"><i class="material-icons">chat</i><span>' +
snapshot.key + '</span></button><br/>';
});
}
// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = function() {
// Shortcuts to Firebase SDK features.
this.auth = firebase.auth();
this.database = firebase.database();
this.storage = firebase.storage();
// Initiates Firebase auth and listen to auth state changes.
this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
// Loads chat messages history and listens for upcoming ones.
FriendlyChat.prototype.loadMessages = function() {
this.messagesRef = this.database.ref('messages/' + chat);
// Make sure we remove all previous listeners.
this.messagesRef.off();
$("#messages").html("");
// Loads the last 15 messages and listen for new ones.
var setMessage = function(data) {
var val = data.val();
this.displayMessage(data.key, val.name, val.text, val.photoUrl, val.imageUrl);
}.bind(this);
this.messagesRef.limitToLast(15).on('child_added', setMessage);
this.messagesRef.limitToLast(15).on('child_changed', setMessage);
};
function click1(name) {
chat = name;
console.log ('test works ' + chat);
this.loadMessages(); // here is the problem!!!!
};
window.onload = function() {
window.friendlyChat = new FriendlyChat();
};
正如您所看到的,我动态创建了click1
函数,我希望当我单击一个对象来重新加载消息时,我想访问FriendlyChat.prototype.loadMessages
。
我已经尝试了什么?
this.loadmessages();
和
FriendlyChat.prototype.loadMessages();
但他们没有工作。有什么办法吗?