从Drupal 7中的模块.js文件调用全局JS函数

时间:2012-06-02 14:39:24

标签: javascript drupal drupal-7

使用great help of Sk8erPeter我设法在节点创建和Drupal 7中某个内容类型的节点更新上执行Javascript代码。

我现在的问题是我无法使用此模块js文件调用函数FB.api。它与Javascript名称空间有关吗?从控制台运行FB.api()函数工作正常......

提前感谢您的帮助。

尼尔斯

1 个答案:

答案 0 :(得分:0)

根据您的评论...我只是看着您的testModule.behaviors.js,它看起来与我写给您here in the other topic的功能相似。

您当前的代码只有这样:

FB.api(
    '/me/shareatear:share',
    'post',
    { tear: document.URL },
    function(response) {
       if (!response || response.error) {
          alert('Error occured');
       } else {
          alert('done. ' + response.id);
       }
    });

Drupal.behaviors在哪里,以及我之前向您展示过的attach函数?所有其他的东西在哪里? :)
当前代码输出错误并不奇怪,因为我认为这个JavaScript文件包含之前甚至定义FB对象,这样你直接调用这段代码标题中的

我认为你的testModule.behaviors.js文件应该是这样的(基于我们之前讨论的代码):

(function ($) {
    Drupal.behaviors.testModule = {
        doitnow: function () {
            alert("A new \"tear\" content has just been added!");

            // change this code to the appropriate one
            FB.api('/me/shareatear:share', 'post', {
                tear: document.URL
            }, function (response) {
                if (!response || response.error) {
                    alert('Error occured');
                } else {
                    alert('done. ' + response.id);
                }
            });

        },

        attach: function (context, settings) {
            try {
                if (settings.testModule.tear_just_added) {
                    this.doitnow();
                }
            } catch (ex) {}
        }
    };
})(jQuery);

因此,请更新您的CURRENT内容(您只需在FB.api"包装")之前调用db_query(),并将其内容更改为此内容。


编辑:

好的,尝试使用以下/** * Implements hook_init() * @see http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_init/7 */ function testModule_init() { // after putting this in your file, save it, delete cache, then COMMENT OUT THE FOLLOWING LINE!!! It should only RUN ONCE (it's enough). db_query("UPDATE {system} SET weight = 111 WHERE type = 'module' AND name = 'testModule'"); } 将此模块的权重设置为更高,因此其挂钩的调用时间晚于其他模块'挂钩。将这些行放入代码后,保存文件,删除Drupal缓存,然后注释掉相应的行!在每个页面加载时都不需要一直运行!

{{1}}