在将骨干模型发送到数据库之前是否有更好的方法来更新它?
在将模型发送到数据库之前,是否有更好的方法使用表单中的值更新模型?我想做这样的事情:
mySave: function () {
this.model.save($(this.el).find(':input').serializeArray());
},
问题是 .serializeArray()
返回一个数组 [{key1:"val1"}, {key2:"val2"}]
,backbone.js model.save()
需要一个对象 {"key1":"val1", "key2":"val2"}
作为参数。
后端是asp.net MVC。我提到这一点只是为了防止有更好的方法将此信息传递回服务器。
目前,我只是迭代序列化数组并一一设置主干模型上的每个属性。
Is there a better way to update a model with the values in the form before sending it to the database? I would like to do something like this:
mySave: function () {
this.model.save($(this.el).find(':input').serializeArray());
},
The problem is that .serializeArray()
returns an array [{key1:"val1"}, {key2:"val2"}]
, and the backbone.js model.save()
is expecting an object {"key1":"val1", "key2":"val2"}
as a param.
The back end is asp.net MVC. I'm mentioning this just in case there are better methods to pass this information back to the server.
Currently, I am just iterating through the serialized array and setting each property on the Backbone Model one by one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚刚写了这个:https://github.com/macek/jquery -to-json
在这里查看它的演示 http://macek.github。 com/jquery-to-json
I just wrote this: https://github.com/macek/jquery-to-json
See a demo of it working here http://macek.github.com/jquery-to-json
它不是默认的 javascript,但 Derick Bailey 确实为主干创建了一个模型绑定插件,
这使您的模型/视图保持同步
如果更新文本字段,它将更新您的模型属性
如果模型属性发生更改,它将更新
在此处查看更多信息:
https://github.com/derickbailey/backbone.modelbinding
现在你不需要通过保存中的任何内容,您的模型都是最新的,只需致电
it isn't default javascript, but Derick Bailey did create a modelbinding plugin for backbone,
which keeps your model / view in sync
if a textfield is updated, it will update your model property
if a model property is changed it will update the view
more info on it here:
https://github.com/derickbailey/backbone.modelbinding
now you don't need to pass anything in the save, your model is up to date, just call
如果您的源是对象数组,则可以使用 json2 (现在在大多数现代浏览器中都是继承的):
来自 json2.js:
If your source is an object array, you can use json2 (now inherint in most modern browsers):
From json2.js: