我怎样才能编写可重用的Javascript? [英] How can I write reusable Javascript?

查看:88
本文介绍了我怎样才能编写可重用的Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始将我的函数包装在Objects中,例如:

I've started to wrap my functions inside of Objects, e.g.:

var Search = {
  carSearch: function(color) {
  },
  peopleSearch: function(name) {
  },
  ...
}

这对可读性有很大帮助,但我仍然遇到 reusabilty 的问题。更具体地说,困难在于两个方面:

This helps a lot with readability, but I continue to have issues with reusabilty. To be more specific, the difficulty is in two areas:


  1. 接收参数。很多时候我会有一个带有多个输入字段的搜索屏幕和一个调用javascript搜索功能的按钮。我必须在按钮的onclick中放入一堆代码来检索然后将输入字段中的值列入函数调用,或者我必须对HTML输入字段名称/ ID进行硬编码以便随后可以检索它们用Javascript。我为此解决的解决方案是将字段名称/ ID传递给函数,然后使用该函数从输入字段中检索值。这很简单,但似乎不合适。

  1. Receiving parameters. A lot of times I will have a search screen with multiple input fields and a button that calls the javascript search function. I have to either put a bunch of code in the onclick of the button to retrieve and then martial the values from the input fields into the function call, or I have to hardcode the HTML input field names/IDs so that I can subsequently retrieve them with Javascript. The solution I've settled on for this is to pass the field names/IDs into the function, which it then uses to retrieve the values from the input fields. This is simple but really seems improper.

返回值。大多数Javascript调用的效果往往是屏幕上的某些视觉直接更改,或者是在调用中执行的另一个操作的结果。当我在功能结束时放置这些屏幕改变效果时,可重用性就是干杯。例如,搜索完成后,我需要在屏幕上显示结果。

Returning values. The effect of most Javascript calls tends to be one in which some visual on the screen changes directly, or as a result of another action performed in the call. Reusability is toast when I put these screen-altering effects at the end of a function. For example, after a search is completed I need to display the results on the screen.

其他人如何处理这些问题是什么?提出我的思考上限让我相信我需要在我的应用程序中的每次使用和我创建的通用方法之间都有一个特定于页面的Javascript层,这些方法将在应用程序范围内使用。使用前面的示例,我将有一个搜索按钮,其onclick调用myPageSpecificSearchFunction,其中搜索字段ID /名称是硬编码的,它会封送参数并调用通用搜索功能。泛型函数只返回数据/对象/变量,不会直接从DOM读取或对DOM进行任何更改。然后,特定于页面的搜索功能将接收该数据并适当地更改DOM。

How do others handle these issues? Putting my thinking cap on leads me to believe that I need to have an page-specific layer of Javascript between each use in my application and the generic methods I create which are to be used application-wide. Using the previous example, I would have a search button whose onclick calls a myPageSpecificSearchFunction, in which the search field IDs/names are hardcoded, which marshals the parameters and calls the generic search function. The generic function would return data/objects/variables only, and would not directly read from or make any changes to the DOM. The page-specific search function would then receive this data back and alter the DOM appropriately.

我是在正确的路径上还是有更好的模式来处理重用Javascript对象/方法?

Am I on the right path or is there a better pattern to handle the reuse of Javascript objects/methods?

推荐答案

基本模式



您的基本模式,我可以建议修改您的结构以使用模块模式和命名函数:

Basic Pattern

In terms of your basic pattern, can I suggest modifying your structure to use the module pattern and named functions:

var Search = (function(){
    var pubs = {};

    pubs.carSearch = carSearch;
    function carSearch(color) {
    }

    pubs.peopleSearch = peopleSearch;
    function peopleSearch(name) {
    }

    return pubs;
})();

是的,这看起来更复杂,但这部分是因为没有涉及辅助功能。请注意,现在,每个函数都有一个名称(您之前的函数是匿名的;它们绑定的属性具有名称,但函数没有,这对调试器中调用堆栈的显示有影响等)。使用模块模式还可以使您具有完全私有的功能,只有搜索对象中的功能才能访问。 (只需在大型匿名函数中声明函数,不要将它们添加到 pubs 。)更多关于我的理由(有利有弊,为什么你可以' t结合功能声明和属性赋值)此处

Yes, that looks more complicated, but that's partially because there's no helper function involved. Note that now, every function has a name (your previous functions were anonymous; the properties they were bound to had names, but the functions didn't, which has implications in terms of the display of the call stack in debuggers and such). Using the module pattern also gives you the ability to have completely private functions that only the functions within your Search object can access. (Just declare the functions within the big anonymous function and don't add them to pubs.) More on my rationale for that (with advantages and disadvantages, and why you can't combine the function declaration and property assignment) here.

我真正喜欢的一个函数来自原型 表格# serialize 函数,它遍历表单元素,并根据字段的名称为每个字段构建一个带有属性的普通对象。 (Prototype的当前 – 1.6.1&nd;–实现有一个问题,它不保留字段的顺序,但令人惊讶的是,这很少是一个问题。)听起来你会这样的事情能够得到很好的服务,而且他们并不难建立;那么你的业务逻辑就是处理具有根据它们所关联的属性命名的对象,并且不知道实际的表单本身。

One of the functions I really, really like from Prototype is the Form#serialize function, which walks through the form elements and builds a plain object with a property for each field based on the field's name. (Prototype's current – 1.6.1 – implementation has an issue where it doesn't preserve the order of the fields, but it's surprising how rarely that's a problem.) It sounds like you would be well-served by such a thing and they're not hard to build; then your business logic is dealing with objects with properties named according to what they're related to, and has no knowledge of the actual form itself.

我倾向于将应用程序视为对象以及它们之间的连接和交互。所以我倾向于创建:

I tend to think of applications as objects and the connections and interactions between them. So I tend to create:


  • 代表商业模式的对象等,不论界面如何(当然,业务模型几乎肯定是由接口部分驱动的)。这些对象在一个地方定义,但同时用于客户端和服务器端(是的,我使用JavaScript服务器端),并设计了序列化(通过JSON,在我的情况下),所以我可以来回发送它们

  • 了解如何使用这些来更新底层商店的服务器端(因为我倾向于处理具有底层商店的项目),并且

  • 对象客户端知道如何使用该信息呈现给UI。

  • Objects representing the business model and such, irrespective of interface (although, of course, the business model is almost certainly partially driven by the interface). Those objects are defined in one place, but used both client- and server-side (yes, I use JavaScript server-side), and designed with serialization (via JSON, in my case) in mind so I can send them back and forth easily.
  • Ojects server-side that know how to use those to update the underlying store (since I tend to work on projects with an underlying store), and
  • Objects client-side that know how to use that information to render to the UI.

(我知道,几乎不是原创!)我试图保持商店和渲染对象的通用性,所以他们主要通过查看业务对象的公共属性来工作(这几乎是所有的属性;我不使用像Crockford这样的模式让你真正隐藏数据,我发现它们太贵了)。实用主义意味着商店或渲染对象有时必须知道他们正在处理什么,特别是,但我确实试图在可能的地方保持通用。

(I know, hardly original!) I try to keep the store and rendering objects generic so they mostly work by looking at the public properties of the business objects (which is pretty much all of the properties; I don't use the patterns like Crockford's that let you really hide data, I find them too expensive). Pragmatism means sometimes the store or rendering objects just have to know what they're dealing with, specifically, but I do try to keep things generic where I can.

这篇关于我怎样才能编写可重用的Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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