Reputation: 3945
Not sure what I am doing wrong here but the basics is:
/** @jsx React.DOM */
/**
* Deal with creating a set of posts for a table.
*/
var PostRow = React.createClass({
handleDelete: function(id){
var postToDelete = AisisWriter.Models.Post();
postToDelete.set({id: this});
posttoDelete.destroy().then(this.deleted, this.fail)
return false;
},
deleted: function() {
console.log('Success - check the db for this post');
},
fail: function() {
console.log('Fail');
},
render: function(){
// Loop through the post objects.
var post = this.props.posts.map(function(postObject) {
var content = null;
var title = null;
// Cut off the text at anything over 140 characters
if (postObject.content.length > 140){
content = postObject.content.substr(0, 140) + '...';
}else{
content = postObject.content;
}
// Cut off the text at anything voer 20 characters
if (postObject.title.length > 20){
title = postObject.title.substr(0, 20) + '...';
}else{
title = postObject.title;
}
// Return the rows of the table.
// React makes us have a unique key.
return (
<tr key={postObject.id}>
<td>{title}</td>
<td>{content}</td>
<td>
<a href={"#/post/" + postObject.id} className="btn btn-primary move-right-10px">View</a>
<a href={"#/post/" + postObject.id + '/edit'} className="btn btn-success move-right-10px">Edit</a>
<button className="btn btn-danger" onClick={this.handleDelete(postObject.id)}>Delete</button>
</td>
</tr>
);
});
// Finially return the rows (note the div)
return (
<div>{post}</div>
);
}
});
The issue I am getting is that if I do: this.handleDelete
life is grand, the page will load. But I need to pass in the id of this particular post id, so I tried doing what you see: this.handleDelete(postObject.id)
how ever at that point I get: Uncaught TypeError: undefined is not a function
on the whole this.handleDelete(postOject.id)
.
Have I entered call back hell? Am I doing something wrong?
Upvotes: 0
Views: 1676
Reputation: 44880
When using Array.prototype.map
, the context of the function falls to the global scope by default, i.e. this
refers to window
in a browser. You can pass a context to map
when you call it to set it to the component like your code expects:
// Add a `this` as the second argument to `map` to set the context to
// the current component. `this.handleDelete` will then refer to the component's
// `handleDelete` function like you are expecting.
var post = this.props.posts.map(function(postObject) {
...
<button className="btn btn-danger" onClick={this.handleDelete.bind(this, postObject.id)}>Delete</button>
...
}, this);
You also need to bind the callback function to pass postObject.id
.
// The current form is a function call
this.handleDelete(postObject.id)
// `bind` returns a new function that will be passed `postObject.id` when it is
// called by React.
this.handleDelete.bind(this, postObject.id)
Upvotes: 2