Adding Items using Xhr

22 views
Skip to first unread message

DAZ

unread,
Aug 7, 2011, 1:55:22 PM8/7/11
to RightJS
I'm trying to add a task to a list using Ajax.
The request is working in the background, but I can't get the returned
html to be inserted into the correct place. I want it to be inserted
into the next list after the form (there are more lists on the page).

This is the code I'm using, but the problem is that 'this' doesn't
refer to the form that was submitted does it? Is there any way to get
access to the form within the onSuccess function?

".list form".onSubmit(function(event) {
event.stop();
this.send({
onSuccess: function() {
this.next().insert(this.responseText);
this.inputs()[0].setValue("").focus();
}
});
});

cheers,

DAZ

Nikolay Nemshilov

unread,
Aug 8, 2011, 12:22:32 AM8/8/11
to rig...@googlegroups.com
You call `this.next()` in a context of an XHR request (the onSuccess callback will be called in there). bind your function to the current context, kinda like that

onSuccess: function() {

}.bind(this)

after that it will always be executed in the context of form.

here is more info about binding

http://rightjs.org/tutorials/functional-programming


--
Thanks,
Nikolay

> --
> You received this message because you are subscribed to the Google Groups "RightJS" group.
> To post to this group, send email to rig...@googlegroups.com.
> To unsubscribe from this group, send email to rightjs+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/rightjs?hl=en.
>

DAZ

unread,
Aug 8, 2011, 3:05:28 AM8/8/11
to RightJS
Thanks Nikolay,

".list form.new".onSubmit(function(event) {
event.stop();
this.send({
onSuccess: function() {
this.next().insert(this.responseText);
this.inputs()[0].setValue("").focus();
}.bind(this)
});
});

This code now adds the html in the right place, but now it can't
access the return html as this.responseText is now referring to the
form rather than the xhr. Is there a way to be able to access both?

cheers,

DAZ

Nikolay Nemshilov

unread,
Aug 8, 2011, 3:10:14 AM8/8/11
to rig...@googlegroups.com
something like this should help

onSuccess: function(xhr) {
  xhr.responseText; // bla bla bla
}.bind(this);


--
Thanks,
Nikolay

DAZ

unread,
Aug 8, 2011, 3:58:20 AM8/8/11
to RightJS
Brilliant, works perfectly now!

I should have remembered that you can use an argument with xhr
functions rather than just use 'this' - I was only reading about it
the other day in the docs!

Thanks loads for the help,

DAZ
Reply all
Reply to author
Forward
0 new messages