Create Jquery plugin

Asked

Viewed 126 times

0

I am creating a jquery plugin and would like to know how to use the div selected in the plugin to be my variable... :

(function ($) {
    $.fn.plugin = function () {
        $(document).ready(function () {
            var video = this;
            video.contextmenu(function () {
                return false;
            });
        });
      };
    })(jQuery);

but it didn’t work, someone can tell me how to do ?

http://jsfiddle.net/aeBYM/

  • Please place all relevant code at the beginning of the question. Note that the code you have is missing the closure of a function };

2 answers

2

In its previous code there was this error, in addition to the wrong use of this within the closure, as indicated in EDIT below.

Using this within the plugin method

In this case, the this is already jQuery’s own object.

I mean, instead of doing this $(this), use only this.

this in this case is the object used to call the method:

$("#xpto").dumb( ... );

In the plugin, this refers to the actual $("#xpto").

Reference:

http://learn.jquery.com/plugins/basic-plugin-creation/

EDIT:

Problem with this na closure

In javascript, the object this is directly linked to the current running method. So you will need to store the jquery object, in a variable, before using it within a closure:

(function ($) {
    $.fn.dumb = function () {
        var _this = this;
        $(document).ready(function () {
            var video = _this;
            video.contextmenu(function () {
                return false;
            });
        });
      };
    })(jQuery);
  • what does that mean ?

  • I edited the answer.

  • I edited my question too, you know why it fails when I use it like this ?

  • if I put var video = $(this); it works but not in the whole script, if I put var video = this; it doesn’t work!!

  • 1

    As you have now edited the question, this answer no longer makes sense... I will edit the answer to the new case.

  • I edited the answer with information about the errors, and a code that should work.

  • 1

    It did work, man: http://jsfiddle.net/aeBYM/1/ ... if there’s a problem, it’s with this method contextmenu. But what he’s being called is.

Show 2 more comments

0

Have you tried:

(function( $ ){ 
    $.fn.dumb = function() {
        $(document).ready(function () {
            var video = this;
        });
    }
)( jQuery );

I believe it may be the difference between $(this) and this, but I haven’t tested the code...

  • edited my question, see if you can get help...

  • puts a complete example, because as you are calling a function "contextmenu" and I do not see its definition, it becomes more complicated to help, if you can not put the real code of your problem, renames variables and summarizes so that we can get a more real view of the problem ;-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.