jQuery and YUI load

jQuery and YUI load

本文关键字:load YUI and jQuery      更新时间:2023-09-26

我在应用程序中使用jQuery和YUI-3.6.0。我正在使用YUI历史模块。我尝试在YUI历史上创建一个包装器,如下所示。(保存在"history wrapper.js"中)

var MyHistory;
(function() {
    YUI().use('history', function (Y) {
        var history = null;
        MyHistory = function() {
            history = new Y.History();
        };
        MyHistory.prototype.save= function() {
            history.add({
                data : "some data"
            });
        };
        MyHistory.prototype.load= function() {
            var data = (history.get("data");
            //process data
        };
    });
})();

我正在使用这个包装与以下代码行

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="yui/yui/yui-min.js"></script>
<script type="text/javascript" src="js/history-wrapper.js"></script>
<script type="text/javascript">
    var jQ = jQuery.noConflict();
    jQ(document).ready(function() {
        var history = new MyHistory();
        history.save();
    });
</script>

我在两个不同的应用程序中使用相同的代码。

  • 在一个应用程序中,当首先加载Wrapper时,一切都很好
  • 在另一个应用程序中,它抛出"MyHistory is not defined",因为在加载包装器之前调用了"jQ(document).ready"函数

我不知道是什么原因导致了这种行为。有人能帮我吗?

YUI.use()中的回调函数"function(Y){…where you define MyHistory…}"仅在加载dependenies(history)时执行。

然后,当您尝试使用包装器时,您无法保证MyHistory已定义。

解决方案可能是将JQuery代码也放在YUI.use()中。您可以让YUI加载程序加载jquery和历史模块,您不再需要包装Histroy插件。

我不确定它到底是这样的(现在无法检查)。

<script type="text/javascript" src="yui/yui/yui-min.js"></script>
YUI({
    modules: {
        'jquery': {
            path: 'js/jquery.js'
        }
    }
}).use('history', 'jquery' , function (Y) {
 var jQ = Y.jQuery.noConflict(); //or juste jQuery.noConflict();
    jQ(document).ready(function() {  //it is likely the document will already be ready
        var history = new Y.History();
        history.save();
    });    
});