我認爲有幾種方法可以通過骨幹來實現。我想我會先有自己的模型來表示混搭:
var MashupModel = Backbone.Model.extend({
});
然後你就可以在任何車型均經過像你通常會(或爲此事的集合):
var my_mash = new MashupModel({
dog: dogModel.toJSON(),
cat: catModel.toJSON(),
foxes: foxCollection.toJSON()
});
// do stuff if you need...
然後做你想做的,當響應返回正常人一樣:
my_mash.save({}, {
success: function(model, response) {
// do stuff here to put new data into the proper models/collections
},
error: function() { alert("I FAIL!"); }
});
這一切都很好。不過,我認爲這將是更好的下推到上述的MashupModel對象,而不是在請求文件VEL。此外,幾種方法:
var MashupModel = Backbone.Model.extend({
initialize: function(attrs) {
// can't remember the actual code, but something along the lines of:
_.each(attrs.keys, function(key) {
this.set(key, attrs.key.toJSON();
});
},
save: function(attrs, opts) {
var callback = opts.success;
opts.success = function(model, response) {
// do your conversion from json data to models/collections
callback(model, response);
};
// now call 'super'
// (ala: http://documentcloud.github.com/backbone/#Model-extend)
Backbone.Model.prototype.set.call(this, attrs, opts);
}
});
或者你可以覆蓋的toJSON(因爲骨幹調用,以獲得ATTRS準備AJAX):
// class definition like above, no initilize...
...
toJSON: function() {
// again, this is pseudocode-y
var attrs = {};
_.each(this.attributes.keys, function() {
attrs.key = this.attributes.key.toJSON();
});
return attrs;
}
...
// save: would be the same as above, cept you'd be updating the models
// directly through this.get('dogs').whatever...
現在,你可以這樣做:
var my_mash = new MashupModel({
dog: dogModel,
cat: catModel,
foxes: foxCollection
});
// do some stuff...
my_mash.save({}, {
success: function(model, response) {
// now only do stuff specific to this save action, like update some views...
},
error: function() { alert("I FAIL!"); }
非常有趣。我很想創建一個像MashupModel這樣的抽象骨幹模型,但在此之前就對社區進行了調查。我想我會試一試,然後報告實驗的進展情況,然後可能接受你的答案。再次感謝! – papdel