当前位置: 动力学知识库 > 问答 > 编程问答 >

spring - Setup knockoutJS view model to bind to one-to-many property

问题描述:

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?

网友答案:

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:

def update = {
 params.put("childObject.id",params.childObjectId)
 params.remove("childObjectId")

 def parentObject = new ParentObject(params)
}

This fetches the related items and builds the object. If you had a lot of related fields, this would become a painful process.

分享给朋友:
您可能感兴趣的文章:
随机阅读: