我收到发送到房间的最后一条消息,这些消息也将显示在View中,但是如果Strophe事件处理程序中出现新消息,虽然我看到传输消息节通过线路(连接上的xmlInput),但是不会触发。
可能是什么原因?
连接后,我创建MessageList并注册Strophe处理程序:
Messages = new MessageList();
XMPPConnection.addHandler(Messages.onMessageReceived, null, "message", "groupchat");
XMPPConnection.send($pres({to: "room@conference.server.local/user1"}).c("x", {xmlns: "http://jabber.org/protocol/muc"}));
window.App = new AppView();
MVC:
// ----------------- Message Model ----------------
var Message = Backbone.Model.extend({
body: "default message",
initialize: function(body) {
if (body) {
this.set({body: body});
}
}
});
// ----------------- Message Collection ----------------
var MessageList = Backbone.Collection.extend({
model: Message,
initialize: function(body) {
},
onMessageReceived: function(body) {
var message = new Message($(body).text());
Messages.add(message);
return true;
}
});
// ---------------- Message View -------------------
var MessageView = Backbone.View.extend({
tagName: "li",
template: _.template($("#message-template").html()),
events: {},
initialize: function() {
this.model.bind("change", this.render, this);
// this.model.bind("remove", this.remove, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
// ---------------- App View -------------------
var AppView = Backbone.View.extend({
el: $("#myapp"),
initialize: function() {
Messages.bind("add", this.addOneMessage, this);
this.main = $('#main');
},
addOneMessage: function(message) {
var view = new MessageView({model: message});
this.$("#message-list").append(view.render().el);
},
});
答案 0 :(得分:1)
有一些问题,这里有一些提示:
您的Message
模型应写为:
var Message = Backbone.Model.extend({
defaults: {
body: "default message",
}
});
如果您传递属性,则无需进行初始化。
您的收藏:
var MessageList = Backbone.Collection.extend({
model: Message,
});
我还将onMessageReceived放在MessageList:
之外 var onMessageReceived = function(body) {
Messages.add({body: $(body).text()});
return true;
}
您的MessageView可以更简单,MUC消息不会更改,只是添加它们:
var MessageView = Backbone.View.extend({
tagName: "li",
template: _.template($("#message-template").html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
希望这足以让你继续......