0

I would like to new obj e.g. newForm = new MyForm(...);

Then I would like to bind the click event to a button.

How can I call back the "newForm" from the click event?


Sample code (Fail to bind):

var MyForm = function(data, targetUrl, targetObj, preload, callback){
    this.data = data;
    this.preload = preload;
    this.targetUrl = targetUrl;
    this.targetObj = targetObj;
    this.callback = callback;
    this.this = this;
    this.bind();
};

MyForm.prototype.submit = function(){
    this.preload;
    $.ajax({
      type: "POST",
      url: this.targetUrl,
      data: this.data
    }).done(function(responseData) {
        if(typeof this.callback === 'function'){
            return this.callback(responseData);
        }
    });
};

MyForm.prototype.bind = function(newTargetObj){
    if(typeof newTargetObj === 'object'){
        this.targetObj = newTargetObj;
    }

    this.targetObj.click(this.clickEvent());
}

MyForm.prototype.clickEvent = function(){
        console.log(this);
        console.log(this.targetForm);
//        this.targetForm.submit();
        alert('click!');
};
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Bergi Apr 29 '14 at 09:48
  • 1
    You've got the wrong `this` context both in the `clickEvent` function and the `done` handler. Also, you must not call `clickEven()` when attaching it as a handler. – Bergi Apr 29 '14 at 09:49

1 Answers1

0

I'm not able to test this at the moment but I believe you should be able to pass an object into the event you have hooked up for the click event. This is shown below.

MyForm.prototype.bind = function(newTargetObj){
    if(typeof newTargetObj === 'object'){
        this.targetObj = newTargetObj;
    }

    this.targetObj.click(this.clickEvent(this.targetObj));
}

MyForm.prototype.clickEvent = function(sender){
        console.log(this);
        console.log(this.targetForm);
//        this.targetForm.submit();
        alert('click!');
};
aaron-bond
  • 3,101
  • 3
  • 24
  • 41
  • Thanks for reply. Seem the code is not work as expected. It got the follow error "Uncaught TypeError: undefined is not a function" –  Apr 29 '14 at 09:06
  • Sorry, I have try it one more time and found I made something wrong. Currently I found that it does can pass the obj to the clickEvent function. However the button click fail to fire. :( –  Apr 29 '14 at 09:31