Pregunta

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!');
};
¿Fue útil?

Solución

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!');
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top