使用 Jquery(甚至只是 Javascript),如何将命令链接在一起
jquery 中有多个函数,您可以执行以下操作: $('#element').each().get('title').othercmd()
如何创建一个类(或一系列类)来复制此行为? 基本上,我想要这样的东西:
test = new Something()
test.generateSection('title').addData('somedata')
什么是正确的?
谢谢
There are several functions in jquery which you can do the following:$('#element').each().get('title').othercmd()
How can I create a class ( or a series of classes ) to replicate this behavior?
Basically, I want to something like this:
test = new Something()
test.generateSection('title').addData('somedata')
What is correct for this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是在每个函数中返回“this”(对象)。所以你可以这样做:
One approach is to return "this" (the object) in each function. So you could do something like this:
只需在每个方法结束时返回您正在操作的内容即可。 (通常是
this
)。Just return the thing that you are operating on at the end of each method. (
this
usually).您只需在您希望能够链接的所有方法中返回当前实例即可实现链模式。
并对“类”的其他方法执行相同的操作。需要记住的是,您必须存储将来调用中需要的对象,在您的情况下,您正在生成一个部分,因此您必须将其放入您的实例中(在某些私有变量中,如sectionAdded),这样您就可以能够继续从其他方法操作它。
You can implement a chain pattern just by returning the current instance in all the methods that you want to be able to chain.
And do the same with the other methods of your "class". Something to keep in mind is that you must store the objects that you will need in future calls, in your case you are generating a section, so you would have to put that inside your instance (in some private variable like sectionAdded) so you will be able to continue manipulating it from other methods.
我不知道是否有一种方法可以轻松地将命令与纯 JavaScript 链接在一起,但如果您想使用 jQuery 尝试此操作,则必须将代码编写为 jQuery 插件。
它实际上非常简单,并且有大量的教程可以帮助您编写自己的插件。
我遇到的最简单的教程之一是本教程:
构建你的第一个jquery-plugin-that.html
I don't know if there is a way to easily chain together commands with plain javascript, but if you wanna try this with jQuery, you'll have to write your code as a jQuery plugin.
It's actually pretty easy and there are tons of tutorials for writing your own plugins.
One of the easiest I came across is this tutorial:
building-your-first-jquery-plugin-that.html