简体   繁体   中英

Override prototype javascript object

I have the following in prototype.js:

    Ajax.Base = Class.create({
    initialize: function(options) {
    alert('in original');
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

I am trying to add another option, but I don't want to modify the existing prototype library, but extend it so that it will have my new option. I have created a second js file that gets loaded after prototype.js that includes the following:

  Ajax.Base = Class.create({
  initialize: function(options) {
    alert('in override');
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true,
      on401: function() { window.location.href="/logout.jsp"; }
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

The alert in the override object never gets called, but it continues to use the original object. I must be missing something or the Class.create is doing things dynamically after I have tried to redefine the object.

I found a way to make it work using Class#addMethods() :

Ajax.Base.addMethods({
    initialize: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true,
      on401: function() { window.location.href="/logout.jsp"; }
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
}); 

You should use the function http://api.prototypejs.org/ajax/Ajax/Responders/register/

Ajax.Responders.register ({
  on401: function() {
      window.location.href="/logout.jsp";
})

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