0

I have a tagging plugin which I am re-factoring.

I keep passing around an object that I construct each time, So, instead I now have a function that I pass the values and it returns the object. This works fine, except now I need access to one of the variables in the plugin.

If you look at the bottom you will see inside _addTag I make a call to this.tag and I want to store the number of elements in the tagArray but my call to this doesn't call the widget.

(function ($) {
    $.widget("ui.tagit", {

        // default options
        options:{},

        //initialization function
        _create:function () {

            var self = this;
            this.tagsArray = [];
            ...

            ...
            this._addTag('label', 'value');

            }

        },


        _addTag:function (label, value) {
            ...

            //THIS IS WHERE THE TAG OBJECT IS CREATED
            var tag = new this.tag(label, (value === undefined ? label : value));
            tag.element = $('<li class="tagit-choice"'
                + (value !== undefined ? ' tagValue="' + value + '"' : '')
                + '>' + label + '<a class="tagit-close">x</a></li>');
            ...
        },

        tag: function (label, value, element) {
            var self = this;
            return {
                label:label,
                value:value,
                element:element,
                index: self.tagsArray.length
            }
        }

    });
})(jQuery);

the call to this is instead:

$.widget.tag
__proto__: Object
constructor: function (label, value, element) {
__proto__: Object
1
  • Ok, found my issue, it was the use of the new keyword. so my next question is. What difference is the new keyword making? Commented May 5, 2012 at 9:40

1 Answer 1

1

Using the new keyword in JavaScript to invoke a function invokes it with its context (this) set to a newly created object.

In your example within the tag function you're expecting this to be set to the widget object you're working with, but instead it will be set to the newly created object because of the use of the new keyword. Therefore, it will fail on self.tagsArray.length because the newly created object doesn't have a tagsArray property.

For more information on the new keyword` I recommend reading the MDN article on it - https://developer.mozilla.org/en/JavaScript/Reference/Operators/new.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.