簡體   English   中英

如何在另一個js文件中調用函數或觸發將參數作為數據對象傳遞給Jquery的自定義事件?

[英]How to call function in another js file or trigger a custom event that passes a parameter as data object in Jquery?

我正在使用reuqireJS,正在努力調用一個函數,該函數位於我需要的js文件中。 我的主要app.js “控制器”需要(plugin)app.js ,它可以處理所有插件配置和插件相關的功能。

這是來自app.js

define([], function(){
    var start = function() {
        require(['jquery', 'overrides', 'jqm', 'multiview', 'respond'],function() {

            // globals
            var 
            // PROBLEM attempt at an external plugin function object
            dataTablesExt = {},
            ...;

            // call for (plugin)app.js
            enhanceDataTables = 
                function( page, from ) {
                    var datatable = page.find('.table-wrapper table');                  
                    if ( datatable.length > 0 && datatable.jqmData('bound') != true ) {
                        datatable.not(':jqmData(bound="true")')
                            .each( function() {
                                var that = $(this),
                                tblstyle = that.jqmData("table-style");

                                that.jqmData('bound', true);
                                require(['services/datatables/app'], function (App) {
                                // this calls (plugin)app.js
                                App.render({style: tblstyle, table: that });
                                });
                            });
                        }
                }; 

        // PROBLEM - try to call function "Hello" inside datatables.app
       anotherFunc= 
                function( page, from ) {
                    dataTablesExt.sayHello("john");
                };

我想我的問題是如何設置全局變量dataTablesExt ,因此我可以用要全局調用的函數“填充”它。 下面是我嘗試內(plugin)app.js

define(['services/datatables/app', 'services/datatables/datatables.min'], function( app, datatables ) {
    function render(parameters) {
    ...
    // the function I want to call
    function helloName( name ){
        alert( name );
        };

    // I'm trying to add this function to the global "dataTablesExt"
    dataTablesExt.sayHello = helloName; 
    }

但是...不起作用。 我總是得到:

  dataTablesExt.sayHello is not a function

題:
有人可以指出我做錯了什么嗎? 如果這不可能,那將是另一種選擇。

我當時想觸發一個自定義事件,但是我將不得不設置一個與事件一起傳遞的對象,但我不知道該怎么做。

感謝幫助!

得到它了。 我需要將dataTablesExt附加到我正在使用的全局變量上,而不是將其聲明為變量。 像這樣:

 // globals
        var 
        ...;

        $.dataTablesExt = {};

然后,我可以為其分配功能並調用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM