简体   繁体   中英

javascript prototype - adding a callback

I'm using the javascript revealing prototype pattern, and I want to add a callback. I'm trying something like:

http://jsfiddle.net/Qyhrb/2/

  var Refinements = function () { };

  Refinements.prototype = function () {
    Init = function () {
      $('.btn').click(Callback);
    },
    Callback = function(){
      alert('default function');
    };
    return { Init: Init, Callback : Callback };
  }();


   var refinements = new Refinements();
   refinements.Callback = function(){ alert('new method'); };
   refinements.Init();

Essentially what I want to do is pass a callback into the object and raise that callback when an event occurs.

    Init = function () {
        var refinement = this;
        $('.btn').click(refinement.Callback || Callback);
    },

Fiddle

var Refinements = function() {};

Refinements.prototype = function() {
  return {
    init: function() {
      $('.btn').click(this.callback);
    },
    callback: function() {
      alert('default function');
    }
  }
}();


var refinements = new Refinements();
refinements.callback = function() {
  alert('new method');
};
refinements.init();

When I separated out the prototype functions, and removed the return { Init: Init, Callback : Callback }; piece everything seems to work fine.

function Refinements() {}

Refinements.prototype.Init = function() {
    $('.btn').click(this.Callback);
};

Refinements.prototype.Callback = function() {
    alert('default function');
};


var refinements = new Refinements();
refinements.Callback = function(){ alert('new method'); };
refinements.Init();​

http://jsfiddle.net/Qyhrb/8/

Foobar = function() {
    this.callBack = function() {
        alert("Default method");
    };
}

Foobar.prototype = {
    Init: function() {
        var self = this;
        $(".btn").click(function() {
            self.callBack.call();
        });
    }
};

var foobar = new Foobar();
foobar.Init();
foobar.callBack = function() {
    alert("Boo!");
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM