我有一个集合和两个模型;
var typeDefault = Backbone.Model.extend({
defaults: {
type: ""
},
constructor: function (attrs, options) {
var parsedResponse = JSON.parse(attrs);
this.attributes = parsedResponse;
},
});
var typeMessage = Backbone.Model.extend({
defaults: {
user: "user",
text: "text"
},
constructor: function (attrs, options) {
var parsedResponse = JSON.parse(attrs);
this.attributes = parsedResponse;
},
});
var chatWebSocketCollection = Backbone.Collection.extend({
initialize: function () {
console.log("chatWebSocketCollection initialized");
},
model: function (attrs, options) {
var type = JSON.parse(attrs);
if (type.type == "message") {
return new typeMessage(attrs, options);
} else {
return new typeDefault(attrs, options);
}
}
});
我希望构造函数根据从集合的'attrs'解析的JSON对象来设置模型的属性。我可以从视图中listenTo
change
个事件。