Proper way to override a JQuery Mobile method in $

2019-05-23 05:54发布

The JQuery Mobile app I'm working on tends to freak out when the soft keyboard launches. I've implemented a solution and it works great, but I had to edit jquery.mobile-1.2.0.js directly to do it. I'd much rather keep my changes in a jquery.mobile.customizations.js file, which extends jQuery Mobile.

I tried to do the following with no success:

delete $.mobile.getScreenHeight;
$.mobile.last_width = null;
$.mobile.last_height = null;
$.mobile.getScreenHeight = function() 
{
   // My modified version
}

I added alert statements into my $.mobile.getScreenHeight, plus the original $.mobile.getScreenHeight. I did see my custom method's alert being fired, but on occasion, it would fire the alert in the original function as well.

Does anyone know the proper way to override a method in $.mobile and also add two new properties?

(Full details about the original issue are in window.resize due to virtual keyboard causes issues with jquery mobile)

Update:

@elclanrs - I've tried to implement the code below with no luck. I've also tried swapping the second and third parameters. Whenever I run the code, it fires my extended getScreenHeight, but then it fires the base getScreenHeight. (I hollowed out the original getScreenHeight and put an alert inside. That alert should never fire.

Open for thoughts!

$.mobile = $.extend( {}, $.mobile, {
    last_width: null,
    last_height: null,
    getScreenHeight: function() {
        // My code...
    }
} );

1条回答
趁早两清
2楼-- · 2019-05-23 06:21

The offending line seems to be a getScreenHeight = $.mobile.getScreenHeight; which places the current definition inside a closure for the resetActivePageHeight function. I'm not sure it's possible to override this directly without editing the file, but you might be able to head it off downstream:

  //simply set the active page's minimum height to screen height, depending on orientation
  function resetActivePageHeight() {
    var aPage = $( "." + $.mobile.activePageClass ),
      aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
      aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
      aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
      aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );

    aPage.css( "min-height", getScreenHeight() - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
  }


  //set page min-heights to be device specific
  $( document ).bind( "pageshow", resetActivePageHeight );
  $( window ).bind( "throttledresize", resetActivePageHeight );

Defining your own resetActivePageHeight then unbinding and binding those again might do the trick. It's a bit messy.

查看更多
登录 后发表回答