CakePHP JS Helper: How to set jQueryObject var outside of view?
I am using the JS helper in Cake 1.3 and due to the need to use jQuery in noConflict mode, I have to set this in开发者_JAVA技巧 every view:
$this->Js->JqueryEngine->jQueryObject = 'jQuery';
I have a LOT of views that rely on this, and I'd like to avoid having to enter this line at the top of every view that needs it. I tried setting the jQueryObject var in my app_controller.php file, but it did not work. I'd rather not hack the core jquery_engine.php file.
Is there a way to set the jQueryObject var globally from within my app?
Thanks!
How I solved it:
I created my own Js Engine helper (views/helpers/my_jquery_engine.php
) with the following code:
App::import('Helper', 'JqueryEngine');
class MyJqueryEngineHelper extends JqueryEngineHelper {
var $jQueryObject = 'jQuery';
}
Then in my app_controller, I say: var $helpers = array('Js' => array('MyJquery'));
Works like a charm.
There's probably no way to set the default value "externally" without breaking MVC constraints. You can simply subclass the JsHelper and customize it internally though:
/app/views/helpers/my_js.php
App::import('Helper', 'Js');
class MyJsHelper extends JsHelper {
public function __construct($settings = array()) {
parent::construct($settings);
$this->JqueryEngine->jQueryObject = 'jQuery';
}
}
This does mean you have to change every instance of $this->Js
to $this->MyJs
, but shouldn't otherwise be a problem.
(Untested solution, since I've never touched the JsHelper, but you get the idea...)
PS: You may also be able to simply subclass the JqueryEngineHelper
directly, overriding the var $jQueryObject = '$';
with var $jQueryObject = 'jQuery';
. Again though, as I've never touched the JsHelper, I don't know if it would cause any problems to rename the class (as you will have to when subclassing).
Why not do this in your layout? That should propgate down to all your views. Just make sure the setting would be below
print $scripts_for_layout;
so that jquery.js would be loaded.
精彩评论