javascript - Backbone 与 Rails 中的模型混搭同步

标签 javascript jquery backbone.js

我有一个 Rails Controller ,它将模型的混搭作为全局 json 对象发送。像这样的事情

{
  dogs : { species: {}, ...},
  cats : { food: {}, ...},
  foxes : { },
  ...,
  ...
}

在我的客户端,我将所有这些实体整齐地划分为不同的主干模型和主干集合。

在某些 onchange 事件中,我需要将一些模型属性的混搭作为 HTTP POST 请求发送回服务器,然后服务器发送一个响应,该响应再次跨越多个模型的值。

如何设置 Backbone.sync 来处理这种 ajax 场景?我不想改变 Rails 后端,因为它的实现相当稳定。或者我是否在我的 Backbone View 之一中通过 jQuery 发出普通 $.ajax 请求,并在 ajax 成功/失败的回调中处理它?<​​/p>

最佳答案

我认为有几种方法可以通过主干来做到这一点。我想我应该从一个模型来代表混搭:

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 对象中,而不是在请求级别。同样,有几种方法:

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 (因为主干调用它来为 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!"); }

关于javascript - Backbone 与 Rails 中的模型混搭同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582465/

相关文章:

javascript - 使用 FusionTables 层关闭 Google v3 API InfoWindow

javascript - 使用 Node Media Server 将 IP cam 的 RTSP 重新流式传输到 http/ws 并以 html 形式显示

javascript - 检查隐藏表单输入在表单提交上是否具有值

javascript - 在 javascript 中使用 "new"

jquery - 将表单数据序列化为 JSON

javascript - 组件/集成测试主干 View 等

Javascript:函数、对象、new ....有点困惑

javascript - map()、reduce() 和 filter 与 forEach()

javascript - 我无法将我的 JQuery 文件链接到我的 HTML 文件

javascript - 纯 CSS 导航栏 :Hover on List not staying