设置knockoutJS视图模型以绑定到一对多属性
我在 grails 中有一个控制器,我正在向它发送一个 ajax JSON 帖子,其中包含 knockoutJS 视图模型。视图模型(以及 javascript 对象)如下所示:
var childProperty= function(name, id) {
this.name = name;
this.id = id;
};
//KnockoutJS - Main view model
var viewModel = {
id: ko.observable(1),
childProperty: ko.observable(new childProperty("Chuck",1))
}
控制器端的数据模型尝试自动使用 Spring 绑定魔法并将 JSON 请求参数绑定到我的数据模型的新实例,如下所示:
def jUpdate = {
def update = new SomeObject(params)
}
问题来了当我希望 Spring 绑定检测到 childProperty.id 是数据模型中的一对多关系并获取数据模型中的相关属性时。 Grails 文档是这样说的:
数据绑定和关联
如果您有一对一或多对一关联,您可以使用 Grails 的数据绑定功能也可以更新这些关系。为了 例如,如果您有传入请求,例如:
/book/save?author.id=20
Grails 会自动检测 .id 请求参数上的后缀并查找 Author 实例 进行数据绑定时给定的 id,例如:
def b = 新书(params)
我正在使用 ko.toJS 实用程序函数,并且简单的属性绑定正确。如何设置视图模型子属性,以便在将其发布到 grails 控制器时,Spring 能够正确检测到它并获取关联的记录并构建对象?
I have a controller in grails that I am sending an ajax JSON post to with a knockoutJS view model. The view model (along with a javascript object) looks like this:
var childProperty= function(name, id) {
this.name = name;
this.id = id;
};
//KnockoutJS - Main view model
var viewModel = {
id: ko.observable(1),
childProperty: ko.observable(new childProperty("Chuck",1))
}
The data model on the controller side is trying to automatically use the Spring binding magic and bind the JSON request parameters to a new instance of my data model like so:
def jUpdate = {
def update = new SomeObject(params)
}
The problem comes in when I want the Spring binding to detect that childProperty.id is a one-to-many relationship in the data model and to go fetch the related property in the data model. The Grails documentation says this:
Data binding and Associations
If you have a one-to-one or many-to-one association you can use
Grails' data binding capability to update these relationships too. For
example if you have an incoming request such as:/book/save?author.id=20
Grails will automatically detect the .id
suffix on the request parameter and look-up the Author instance for
the given id when doing data binding such as:def b = new Book(params)
I am using the ko.toJS utility function and the simple properties are binding correctly. How can I set the view model child property up so that when it is posted to the grails controller, Spring detects it properly and fetches the associated record and builds the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我永远无法让自动弹簧绑定工作,所以我只是传递了子对象的 id 并在服务器端的参数映射中手动设置它们。之后,GORM 适当地获取记录。像这样的事情:
这会获取相关项目并构建对象。如果你有很多相关领域,这将成为一个痛苦的过程。
I was never able to get the automagic spring bindings to work, so I just passed over the id for the child objects and manually set them on the server side in the params map. After that, GORM fetches the record appropriately. Something like this:
This fetches the related items and builds the object. If you had a lot of related fields, this would become a painful process.