在来自HTML元素(如onclick处理程序)的RequireJs模块中调用方法 [英] Calling methods in RequireJs modules from HTML elements such as onclick handlers

查看:785
本文介绍了在来自HTML元素(如onclick处理程序)的RequireJs模块中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将项目从旧浏览器式模块结构更改为新浏览器 - - 服务器端-javascript 模块结构 require.js



在客户端,我使用的是离线托管的jQuery,所以我从他们在使用优先配置技术中给出的示例开始自述文件:

 < title>我的页面< / title> 
< script src =scripts / require.js>< / script>
< script>
require({
baseUrl:'scripts',
paths:{
jquery:'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2 /jquery.min',
jqueryui:...,
...
... //在这里聚集更多路径
},
priority:[' jquery']
},['main']);
< / script>

这实际上可以正常工作。但是我想将主要功能导出到HTML网页本身。例如:

 < a class =buttonhref =#onclick =MyApi.foo(); > 
< img src =foo.pngalt =foo/>点击查看:< b> Foo!< / b>
< / a>

在适应AMD模块模式之前,我通过创建一个字典对象在全局空间中:

  // main.js 

var MyApi = {};

jQuery(document).ready(function($){
// ...未导出的代码在这里...

//通过MyApi导出函数
MyApi.foo = function(){
alert(Foo!);
};
});

但我不知道require.js中正确的方法是什么。可以在< script> 标签内放入更多的 require 语句,然后命名模块为它可以在网页中使用?或者应该总是在main.js中动态地完成,比如 $('#foobutton')。click(...)


使用AMD的一个好处是不需要名称空间。试图用RequireJS再次创建它们将违背AMD推出的模式。


关于使用 main.js ,只有当你有一个页面的应用程序,并且你的所有代码都可以从一个地方引用时,这才是真正合适的。您可以随意拨打额外的电话,以便在需要时加载其他模块。



使用上面的示例,您可以通过以下方式访问它:



foo.js $ b

  define([ jquery'],函数($){

//一些设置
//此处的代码

//返回模块的方法
return {
bar:function(){

}
}


});

page.js

  require(['foo'],function(foo){

// foo模块可以自由使用它的jQuery
$('。button')。on('click',function(e){
foo.bar();
e.preventDefault();
});

});

然后在你的页面请求带有require的page.js文件。



使用上面的示例:

  require({
//在这里配置的东西
},['page']);

或者在页面中进一步加载:

 <脚本> 
require(['page']);
< / script>

其他要点


  • 使用上面的模式,page.js可以很容易地需要许多其他
    模块来加载其他页面相关的功能。


  • 在将成员附加到全局名称空间之前,您现在
    将该代码拆分为单独的模块,可以在
    的任何页面上重新使用它们。所有这些都不依赖于全局对象。

  • 使用require这种方法将事件附加到您的DOM元素中
    最可能是依赖RequireJS提供的DOM Ready模块

    I'm changing a project from an "old" browser-style module structure to a "new" browser-or-server-side-javascript module structure with require.js.

    On the client I'm using an offsite hosted jQuery, so I started from the example they give in the "use priority config" technique of the README:

    <title>My Page</title>
    <script src="scripts/require.js"></script>
    <script>
    require({
        baseUrl: 'scripts',
        paths: {
            jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
            jqueryui: ...,
            ...
            ... // bunch more paths here
        },
        priority: ['jquery']
    }, [ 'main' ]);
    </script>
    

    This is actually working all right. But I'd like to export functionality from main to the HTML webpage itself. For instance:

    <a class="button" href="#" onclick="MyApi.foo();">
        <img src="foo.png" alt="foo" />Click for: <b>Foo!</b>
    </a>
    

    Before fitting into the AMD module pattern, I'd exposed functionality from my various files by creating a dictionary object in the global space:

    // main.js
    
    var MyApi = {};
    
    jQuery(document).ready(function($) {
        // ...unexported code goes here...
    
        // export function via MyApi
        MyApi.foo = function() {
            alert("Foo!");
        };
    });
    

    But I don't know what the right approach in require.js is. Is it okay to put in the HTML more require statements inside of <script> tags, and then name modules so that it can be used from within the webpage? Or should this always be done dynamically inside of main.js, like $('#foobutton').click(...)?

    解决方案

    One benefit from using AMD is to drop the need for namespaces. Trying to create them again with RequireJS will go against the patterns AMD promotes.

    With regard to using main.js, this is only really appropriate when you have a single page app and all your code be reference from one place. You're free to make additional calls to require and load other modules as you need them.

    Using your example from above, you could approach it this way:

    foo.js

    define(['jquery'], function($) {
    
        // Some set up 
        // code here
    
        // Return module with methods
        return {
            bar: function() {
    
            }
        }
    
    
    });
    

    page.js

    require(['foo'], function(foo) {
    
        // jQuery loaded by foo module so free to use it
        $('.button').on('click', function(e) {
            foo.bar();
            e.preventDefault();
        });
    
    });
    

    Then in your page request the page.js file with require.

    Using your example above:

    require({
        // config stuff here
    }, [ 'page' ]);
    

    Or loading it in the page further down:

    <script>
        require(['page']);
    </script>
    

    Some additional points

    • Using the pattern above, page.js could easily require many other modules to load other page related functionality.

    • Where before you would attach members to your global namespace, you now split that code into separate modules that can be re-used on any page. All without reliance on a global object.

    • Using require this way to attach events to your DOM elements will most likely rely on the DOM Ready module provided by RequireJS

    这篇关于在来自HTML元素(如onclick处理程序)的RequireJs模块中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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