Lan*_*ard 6 api jquery plugins scopes
我想创建一个带有这样的API的jQuery插件:
$("#chart").pluginName().attr("my_attr");
Run Code Online (Sandbox Code Playgroud)
而不是这些:
$("#chart").pluginName_attr("my_attr");
$.pluginName.attr("#chart", "my_attr");
Run Code Online (Sandbox Code Playgroud)
基本上,而不必每个命名空间,作用类似于那些在jQuery的方法,我想"范围"的方法,以自定义的API,其中$("#chart).pluginName()会返回一个对象,使得get,attr,find,和其他几个人将被彻底改写.
我确信这不是一个很受欢迎的想法,因为它打破了惯例(是吗?),但它比上面的两个选项更容易,更易读,也可能更优化.你的想法是什么?
我正在尝试这个想法。
\n\n看起来你可以只修改插件接收的 jQuery 对象的函数,然后返回它。
\n\n像这样的东西:
\n\n$.fn.tester = function() { // The plugin\n\n this.css = function() { // Modify the .css() method for this jQuery object\n console.log(this.selector); // Now it just logs the selector\n return this; // Return the modified object\n }\n return this; // Return the modified object\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\nhttp://jsfiddle.net/EzzQL/1/ (也从原始版本更新为覆盖 .html())
\n\n$.fn.tester = function() {\n this.css = function() { \n console.log(this.selector); // This one logs the selector\n return this;\n }\n this.html = function() {\n alert(this.selector); // This one alerts the selector\n return this;\n }\n return this;\n};\n\n// Because .css() and .html() are called after .tester(),\n// they now adopt the new behavior, and still return a jQuery\n// object with the rest of the methods in tact\n$(\'#test1\').tester().css().html().animate({opacity:.3}); \n\n\n// .css() and .html() still behave normally for this one\n// that doesn\'t use the plugin\n$(\'#test2\').css(\'backgroundColor\',\'blue\').html(\'new value\');\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:
\n\n或者,如果您要缓存应应用自定义方法的元素,则可以在.apply()使用它们之前先缓存这些方法。
以上面的示例为基础:
\n\nvar $test1 = $(\'#test1\'); // Cache the elements\n\n$.fn.tester.apply($test1,[this]); // apply() the new methods\n\n$test1.css().html().animate({opacity:.3}); // Use the new methods\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\x8b
\n| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |