4

I need to add some function that returns a value to a dom element. I tried to use jquery's bind method, but it seems that events always return a jquery collection.

My goal is creating a flashcard application. So I created flashcard objects that contain methods and variables including the dom element representing the flashcard on the page. As long as I only work on the dom element (moving around etc.) everything is fine but at some point I need to get a reference to the actual card object to access the additional functionality. Here is the constructor I came up with:

    function make_flashcard {  
        var dom_element;
        function some_function() {}
        /*...other variables and functions */

        var card = {
            dom_element: dom_element,
            some_function: some_function,
            /*...other variables and functions */
        };

        return card;
    }

later I'd like to be able to invoke some_function from outside, maybe like this:

    card = dom_element.get_card();
    card.some_function();

I tried the following three approaches of defining get_card inside make_flashcard, all of which failed:

    dom_element.get_card = function () {
        return card;
    };

    dom_element.prototype.get_card = function () {
        return card;
    };

or

    dom_element.bind("get_card", function () {
        return card;
    });

and then calling

    card = dom_element.trigger("get_card");

If you have any tips to get this running I'd be very happy. Or do you think the whole thing should be approached differently?

Thanks in advance, Dominik

`

1 Answer 1

4

What if you extended the jQuery collection prototype instead?

$.fn.flashcard = function () {
    var self = this;

    if (!this.data("flashcard")) {
        this.data("flashcard", {
           element: self,
           some_function: some_function,
           /*...other variables and functions */
        });
    }

    return this.data("flashcard");
};

Then you could use it like:

var card = $("div.myClass").flashcard();
card.some_function();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot!! That was very helpful. The data method was exactly what I was looking for and with the plugin it also looks nice :-). It took me some time to figure it out, but now it works.

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.