Could you tell me why this will not work? (note the this keyword)
var post = {
url: 'http://myurl.com',
add: function() {
window.location = this.url + '/add';
},
edit: function() {
window.location = this.url + '/edit';
}
};
Somewhere else in the code:
post.url = '<?php echo BASE_ADMIN . $postType ?>';
$(document).ready(function() {
$("#listing").aJqueryPlugin({
...
// Buttons and their callbacks
buttons : [
{name: 'Add', bclass: 'add', onpress : post.add},
{name: 'Edit', bclass: 'edit', onpress : post.edit},
],
...
});
The line
post.url = ….
behaves as expected. The url property in post is updated.
However, when I click on the Add or Edit buttons, and I enter their functions, this.url is undefined because this references the button instead of the post object. Why? What should I do then to reference the url property from a callback?
Since you’re using jQuery, you can use
$.proxy.This returns a new function that will call the method of the object named by the string.
It’s effectively doing this:
Because the value of
thisin a function is dependent on how the function was called, you sometimes need alternate means to ensure that you get the correct value.You could also set these in your original object, as long as you know you always want
thisto refer to that object.This uses the other signature of
$.proxy, which lets you pass the function directly followed by the desiredthisvalue.