Drupal行为 [英] Drupal behaviors

查看:97
本文介绍了Drupal行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 什么是Drupal行为?

  • 向模块开发人员提供什么类型的服务层?

  • 什么类型的关系映射到 jQuery.ready


  • 解决方案

    长版本:Drupal.behaviors不仅仅是替代jQuery.ready,因为后者只运行一次(当DOM准备好进行操作时):可以多次触发行为在页面执行期间,每当新的DOM元素插入到文档中时都可以运行。



    此外,模块可以覆盖或扩展现有行为(例如,如果一个模块有一个行为在所有链接上添加反弹效果,第二个模块可以通过不同的反弹效果来替代行为。)



    简版:更多






    此外,从Drupal 7开始,使用 drupal_add_js (PH P)或 Drupal.settings.modulename (Javascript)直接作为第二个参数(第一个是上下文)传递给该行为。



    例如:

      Drupal.behaviors.changeLinks = function(context,settings){
    if(!settings )settings = Drupal.settings.changeLinks;
    $(a,context).hover(function(){
    $(this).css('color',settings.color);
    });
    };

    如果您的一个脚本(或另一个)创建新节点,那么它仍然可以应用行为到新节点,而不必知道安装了其他模块:

      var newNodes = $('< a href = #>> Hello< / a>< a href =#> World< / a>')。appendTo('#someDiv'); 

    Drupal.attachBehaviors(newNodes);


    • What are Drupal behaviors at all?
    • What type of service layer it offers to module developers?
    • What type of relation it maps to jQuery.ready?

    解决方案

    Long version: Drupal.behaviors is not simply a replacement for jQuery.ready since the latter only runs once (when DOM is ready for manipulation): behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.

    Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a bounce effect on all links, a second module could replace the behavior by a different bounce effect).

    Short version: it's more modular, though the documentation could be improved.


    Also, starting in Drupal 7, settings defined using drupal_add_js (PHP) or in Drupal.settings.modulename (Javascript) are directly passed as second parameter (the first one being the context) to the behavior.

    For example:

    Drupal.behaviors.changeLinks = function(context, settings){
        if (!settings) settings = Drupal.settings.changeLinks;
        $("a", context).hover(function() {
            $(this).css('color', settings.color);
        });
    };
    

    And if one of your script (or another) creates new nodes, it could still have the behaviors applied to the new nodes without having to know what other modules are iinstalled:

    var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');
    
    Drupal.attachBehaviors(newNodes);
    

    这篇关于Drupal行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆