问题
I am creating a personal website using durandal and knockout with the below code to bind a edit blog page. Everything worked great and I was able to bind the text area with the returned text of the ajax call.
Once this was done I was curious if a long response from the webservice would break it, so I put in a Thread.Sleep(1000) into the service and now I cannot get it to bind the returned text to the text area. Any suggestions on how to get this to work???
side-note: I dont think this has to do with the durandal framework but I thought I would include that I am it
javascript
define(['services/logger', 'services/wysiwyg'], function (logger, wysiwyg) {
var postObservable = ko.mapping.fromJS({});
var vm = {
activate: activate,
post: postObservable,
};
return vm;
function activate(routeData) {
var id = routeData.id;
$.ajax(
{
type: "GET",
url: '/api/blog/get',
data: { id: id },
dataType: "json",
})
.then(function(data){
ko.mapping.fromJS(data, postObservable);
});
}
});
c#
public class BlogController : ApiController
{
public IBlogRepository _blogRepository;
public BlogController(IBlogRepository blogRepository)
{
_blogRepository = blogRepository;
}
public BlogModel get(int id)
{
//Thread.Sleep(1000); <-- breaks when uncommented!!!
return ConvertToModel(_blogRepository.ById(id));
}
private BlogModel ConvertToModel(BlogPost b)
{
return new BlogModel { DateCreated = b.DateCreated, Title = b.Title, Content = b.Content, Id = b.Id };
}
}
html
<section>
<div class="row">
<textarea class="sceditor span12" data-bind="html: post.content"></textarea>
</div>
<div class="row">
<button type="button" class="btn offset10 span1">Cancel</button>
<button type="button" class="btn btn-primary span1">Save</button>
</div>
</section>
回答1:
An ajax call is an asynchronous task so you should return a promise. Doing it that way will make Durandal wait until the ajax call finishes.
return $.ajax(
{
type: "GET",
url: '/api/blog/get',
data: { id: id },
dataType: "json",
})
.then(function(data){
ko.mapping.fromJS(data, postObservable);
});
来源:https://stackoverflow.com/questions/16051727/long-ajax-call-breaking-knockout-binding